Define What'S JSX?: Javascript and HTML (Kind of HTML)
Define What'S JSX?: Javascript and HTML (Kind of HTML)
Define What'S JSX?: Javascript and HTML (Kind of HTML)
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.
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)
Basic examples
HTML
<p id=”my-name”></p>
JavaScript
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.”
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'}}/>
<div style="max-width:20vw;min-height:50px"></div>
<div style={{maxWidth:’20vw’,minHeight:50}}></div>
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>
style.css
.my-profile{
width:200px;
}
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>
);
}
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.
HTML
<img src=“/profile.png”></img>
JSX
<img src={"/profile.png"} alt="profile" />
{/* or we can also do */}
<img src="/profile.png" alt="profile" />
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" />
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"
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.
JavaScript
// AND
true && true // true
true && false // false
false && false // false
// OR
true || true // true
true || false // true
false || false// true
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)
// Another example
(protocolUsed ==="https") ? alert("You are secure") : alert("You are not
secure");
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>
);
}
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" />;
}
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>.
// 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>
);
If we write JSX without importing the React package, the program work but show a warningFalse