Define What'S JSX?: Javascript and HTML (Kind of HTML)

Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1of 14

Define what’s JSX?

JSX is a extension to JavaScript syntax usually used with React to describe what the UI should
look like. (JS XML jsx n est pas ,ecassaire pour cree une app react mais il rend le code simpler and
elegent and it transpiles to js pour que les browsers understand)
JSX may remind you of a template language, but it comes with the full power of JavaScript.

JSX and HTML


If you take a look at the App.js which is inside the src folder, you will find a combination of
JavaScript and HTML (kind of HTML).
Inside the function App in the “return” statement, You will find a code that looks like HTML.
Notice when you edit that code, the page refreshes automatically in the browser. That’s called Live
Reload or Hot Reload.

JSX and HTML


Take a look at the function App, You probably wondering why HTML is weirdly inside JavaScript.
This funny tag syntax is neither a string nor HTML. It’s called JSX.
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}

How does it work?


At a first look JSX and HTML looks very similar, but in reality they are very different. working
with JSX makes dynamically manipulating the html element too much easier.
Since every website is made of HTML and browsers only understand HTML (not JSX), you might
be wondering where is the link between JSX and HTML?
Tip: if you inspect the source code of the React webpage in your browser, you will find only HTML
not JSX.
How does it work

Thanks to React, JSX is transformed to html then it gets injected into an HTML element (root) in
the one and only HTML page, the index.html.
This injection is actually happening in the index.js file thanks to ReactDOM. This process happens
only one time, because the App is the only root component in our case (we usually need only one
root component)

JSX and HTML recap


Let’s recap !
• The injection of a component inside an HTML element is called rendering.
• In React, we usually have only one root component (called App).
• We only need one root component to build a React website.
• The root component (App.js) is the entry point of React.
• We only need one HTML file called index.html in any single-page application (like React).
• JSX is compiled and rendered inside the root element in the index.html.
JSX is a programming langage False
JSX is only used with react False
What’s rendering? Is the injection of a component into html

Basic examples
HTML
<p id=”my-name”></p>

JavaScript

let firstName = 'Will';


let lastName = 'Smith';
document.getElementById('my-name').innerHTML = firstName + ' ' + lastName;
JSX

let firstName = "Will";


let lastName = "Smith";

return <p>{firstName + " " + lastName}</p>;

To use an expression (operation or variable) inside JSX, you just need to add curly brackets {}

JSX type
As we already said JSX is about writing HTML inside of JavaScript files, so it inherits all the
JavaScript power.
Well in JavaScript, we can assign mostly everything into variable, using JSX that fact remain valid.
We can create a JSX element and assign it to variable. The example below will explain it more :
function App(){
let input = (<input type='text' placeholder='Name'/>);
let button = <button>Submit</button>;
let form = (
<form>
{input}
{button}
</form>
);

return form;
}

JSX type
Since JSX can be stored in a variable, we can also return it in a function.
Here’s how :
function App() {
// We can put functions inside other functions when they are related
function createForm() {
let input = <input type="text" placeholder="Name" />;
let button = <button>Submit</button>;
return (
<form>
{input}
{button}
</form>
);
}
return <div>{createForm()}</div>;
}

Calling Function
HTML
<p id=”my-age”></p>
JavaScript
document.getElementById(“my-age”)
.innerHTML= getAge(1996)

JSX
<p>{getAge(1996)}</p>

If you need to call a function (any function) ? you just need to call it inside curly brackets {}.
Note: We didn’t declare the getAge() function for simplicity.
We can write an expression or an assignment directly into JSX False
The type of variable containing JSX is object
Is this JSX code right ? False
let user = { name: "John" };
function getName() {
return user.name;
}
function App() {
return (
<div>
<p>{getName}</p>
</div>
);
}

Attributes: style
Now, we are going to learn how to style JSX elements. It’s slightly different than normal HTML.
• These are some of the rules to keep in mind:
• Apostrophes ‘ or quotes “ on strings
• Camel case (See next page)
• Commas (,) instead of a semicolon (;)
• Two curly brackets {{}} instead of quotes “”

HTML
<h1 style= "color:red; font-size:60px">
...
</h1>

---> JSX
<h1 style={{ color: "red", fontSize: 60 }}>...</h1>
What's Camel Case?
You probably wondering what camelCase is.
“It’s the practice of writing phrases in a single “word” with no spaces. We use it to write
variable names in JavaScript.”

The concept is very simple. There are 2 simple rules to follow:


1. No spaces, no underscores ( _ ) and no dashes (-)
2. If the variable is composed of multiple words, all words begin with a Capital letter except
the first word.

Examples
Let’s see more styling examples.
We will find the HTML version on the top and under it the JSX version

html
<div style='text-align:center'/>

JSX
<div style={{textAlign:'center'}}/>

html
<div style="transform:translateX(25px)"/>

JSX
<div style={{transform:'translateX(25px)'}}/>

html
<div style="box-shadow:0 5px 8px #000"/>

JSX
<div style={{boxShadow:"0 5px 8px #000"}}/>
The mesures Units in JSX:
Some CSS properties can take a number, it will have px (pixels) as a unit by default. If you need to
specify a different unit, you have to use the string type.

html
<div style=”height:10px”/>

JSX
<div style={{height:'10px'}}/>

html
<div style=”height:10px”/>

JSX
<div style={{height:10}}/>

html
<div style=”height:10vw”/>

JSX
<div style={{height:'10vw'}}/>

The keyword using to style a jsx element is :style

What should this styling become in JSX ?

<div style="max-width:20vw;min-height:50px"></div>
<div style={{maxWidth:’20vw’,minHeight:50}}></div>

Instead of using semicolon ; in the style attribute we use the ,True

ClassName
The other way to style html elements is using the css classes. In JSX to use the css class we need to
change the attribute class into className, since the keyword class is reserved in JavaScript
html
<div class=”colorful”>...</div>

JSX
<div className='colorful'>...</div>

Attributes: style file


Since we can affect css classes to JSx elements, we can also use the external files to style these
elements.
Try to create a file called style.css.

style.css
.my-profile{
width:200px;
}

Then, all you need to do is import the file like this :

JSX (at the top)


import "./styles.css";

Attributes: style file


Now, let’s create the profile photo and give it a className my-profile to apply the css style.

App.js
function App() {
let firstName = "Will";
let lastName = "Smith";
return (
<div>
<img src="/profile.png" className="my-profile" alt='Will Smith'/>
<p>
{firstName} {lastName}
</p>
</div>
);
}

What does this snippet becomes in JSX:

<div class="funny colorful"></div>

<div className="funny colorful"></div>

<div className={"funny colorful"}></div>


If we use a class instead of className react generate an: warning

When we want to import a file style.css in the App.js, what should we do ?

Import the file at the top of the App.js

The import of a CSS file in JSX must be named? False

Attributes: src
The src attribute is also available in JSX but it's slightly different than HTML. There are a
multiple way to assign a value to the src attribute.

Hard-coded string (not a variable)

HTML
<img src=“/profile.png”></img>

JSX
<img src={"/profile.png"} alt="profile" />
{/* or we can also do */}
<img src="/profile.png" alt="profile" />

Variable (can be a number, object, array, etc...)

HTML
// We need DOM functions to do it
// like setAttribute()

JSX
<img src={myProfileImageUrl}></img>

Attributes in JSX are very similar to html. We just need to replace quotes "" with curly brackets {}.

Adding an image
o display an image on the page, we use the <img/> tag.
This tag requires an src attribute, it’s the path to the image. In React, this path can be set in two
ways, depending on which directory the image is in:
1. 📁public directory
2. 📁src direThe "public" directory
If you add the image in the 📁public directory, you need to reference it in the src attribute with an
absolute url (as a string).
Tips
• Make sure you add the forward slash “/”, it’s called the root.
• If your image is inside a subfolder called 📁images inside the 📁public folder, you need to
specify it
• <img src=”/subfolder/myImage.png”/>

JSX
<img src="/myImage.png" alt="myimage" />

📁The "src" directory


If you add the image in the 📁src directory, you need to import it (using a relative path to src) then
set it in the src attribute of the <img/> tag.
Tips
• Add the dot “.” and forward slash “/”, when importing an image inside src.
JSX
import myWonderfulImage from "./myImage.png"
function App(){
return <img src={myWonderfulImage} alt ='myImage' />
}

More Tips:
Things to keep in mind when importing the image using “import”:
• If your image is in the same folder as your current file:
• ./myImage.png
• If your image is in the parent folder:
• ../myImage.png
• If your image is inside a subfolder:
• ./subfolder/myImage.png

JSX
import myWonderfulImage from "./myImage.png"

If we have an image inside this path: /MyProject/src/assets/icons/icon.svg Do we have to import the


image using “import”? True

If we have an image inside this path: /MyProject/public/assets/icons/icon.svg Do we have to import


the image using “import”?False
If we have an image inside this path: /MyProject/public/assets/icons/icon.svg . What should we add
in the JSX? <img src="/assets/icons/icon.svg"/>

Array Function map


One of the best features that JSX offer is the possibility of using the iterator operator to render
elements dynamically.
Let’s suppose that we have an array of elements that we want to display all in the same way, we can
use the map method to do so.

HTML
<div id="list"></div>

JavaScript
let arr = [1, 2, 3]
for (var i = 0; i < arr.length; i++) {
append('<div>”+arr[i]+”</div>')
}

----->

JSX (ES6)
{
[1, 2, 3].map(currentValue => (
<div>{currentValue}</div>
))
}

After compilation
<div>1</div>
<div>2</div>
<div>3</div>

Old way
Rendering elements conditionally is one of the vital approaches in creating SPA, luckily, React give
us the ability to do so perfectly.
Let’s take a look at the example below.
What if we want to show the form every day in the week except for Sunday? We can do that with
if/else condition.

JSX
function App() {
if (isSunday) {
return <p>We are closed!</p>;
}
// the else is implicit (since the first case has a return
return createForm();
}

Note : Keep in mind that there is a better way to do this. We will see it right away.

Conditional operators with JSX


Let’s remember the logical operator in JavaScript

JavaScript
// AND
true && true // true
true && false // false
false && false // false

// OR
true || true // true
true || false // true
false || false// true

// Booleans from other types


!0 // true
!50 // false, since 50 !== 0
!"" // true
![] // false
!"hello" // false, since “hello” !== “”

Conditional operators: AND/OR


The logical operator && and || are very handy when dealing with implicit if. We will use that in
JSX to simplify it. Read the code and comments below.

JSX
// Ask the user for a URL
let websiteUrl = prompt("Type in your URL");

location.href = websiteUrl;
// Redirects the user to the websiteUrl
// The problem with this example is that the user can leave the field empty
(which means websiteUrl is // empty)

location.href = websiteUrl || 'http://google.com';


// Redirect the use to Google if it’s empty
// Now, if the user left the field empty, we will redirect him to Google.
Otherwise he will be
// redirected to websiteUrl

// Or we can use the AND operator

websiteUrl && (location.href = websiteUrl);

// If the websiteUrl is not empty, redirect to it. Otherwise


// do nothing
Conditional operators: If/else with JSX
The logical operator && and || are very useful when it come to simple if statement, but when it
comes to an if else statement, we better use the ternary operator
// Ask the user for a URL
let websiteUrl = prompt("Type in your URL");

// Check if http exists in the url, add it otherwise


let protocolUsed = (websiteUrl.startsWith("https")) ? "https" : "http";

// Another example
(protocolUsed ==="https") ? alert("You are secure") : alert("You are not
secure");

Conditional operators: Logical expressions


Let’s go back to JSX, to apply logical operators in a real example.
The form in this example only shows up when the firstName is empty.
const firstName = prompt("type your first name");

function App() {
return (
<div>
<p> Hello {firstName || "Anonymous"} </p>
<p> It looks like you {firstName ? "have" : "don’t have"} a name</p>
{!firstName && (
<form>
<p> Type your name here </p>
<input type="text" />
</form>
)}
</div>
);
}

What is the result of this expression ? 2

let a = (1>2) ? (""||"hello") : (0 || 2)


console.log(a)

What is the result of this expression ? “images/defaultPhoto.png”


let user = {
firstName: "John",
lastName: "Smith"
};
let photoPath = user.profilePhoto || "/images/defaultPhoto.png";

console.log(photoPath);

With implicit if/else, can we use multiple AND (&&) and OR (||) in the condition part ? Yes
Not importing React
When using JSX, the React library needs to be imported because JSX tags are compiled to
React.createElement() instructions.
If React is not imported, an error will occur saying “Cannot read property 'createElement' of
undefined”.

App.js
The wrong way:
function App() {
return <img src="/profile.png" className="my-profile" alt="myprofile" />;
}

The right way:


import React from "react";

function App() {
return <img src="/profile.png" className="my-profile" alt="myprofile" />;
}

No adjacent nodes
One of the common mistakes made in JSX, is using multiple root elements (when returning or
creating JSX tags). This is a limitation in JSX. To fix this, we should use a <div>, empty tag
(<></>) or <React.Fragment>.

The wrong way:


return (
<img src="/profile.png" className="my-profile" />
<p>{firstName} {lastName}</p>
)

The right way:


return (
<div>
<img src="/profile.png" className="my-profile" alt="myprofile" />
<p>
{firstName} {lastName}
</p>
</div>
);

// or this way
return (
<>
<img src="/profile.png" className="my-profile" alt="my profile" />
<p>
{firstName} {lastName}
</p>
</>
);
// this is another way
return (
<React.Fragment>
<img src="/profile.png" className="my-profile" alt="my profile" />
<p>
{firstName} {lastName}
</p>
</React.Fragment>
);

Use class instead of className


Using CSS classes in JSX requires setting the className attribute unlike the class attribute in
HTML. This is made by design to avoid the conflict with the keyword class in ES6 Classes.
The wrong way:
return (
<img src="/profile.png" class="my-profile" />
)

The right way:


return (
<img src="/profile.png" className="my-profile" alt="myprofile" />
);

Can we add the attribute style to the <React.Fragment> or <> ? False


What should we use to wrap a group of JSX elements ? (PS. we don’t need any attributes in the
parent) <> <React.Fragment>

If we write JSX without importing the React package, the program work but show a warningFalse

You might also like