Hello there! 👋
Today I am writing about JSX and React elements.
In Learning React : JSX post I discussed my understanding of JSX. But today I will dive deeper with React Documentation on JSX and will check how we create React elements, use it with JSX and render using React DOM. 💪
JSX is a syntax extension for JavaScript which lets us write HTML like markup inside a JS file. It is just syntactic sugar that makes our development easier.
Let's first prepare our project to work with it. In the Installing React with Vite post we learned about installing react to our local machine. I have removed all the folders and files from src folder except App.jsx
and main.jsx
. Here is the github link of the skeleton project.
We know that React doesn't work with DOM and DOM elements. React has it's virtual DOM and it creates React elements.
Now let's create a simple React element in the main.jsx
file.
import React from 'react'
const element = React.createElement('h1', null, 'Hello, world!');
console.log(element);
main.jsx
file is our main file in the React project.
Let's see in the browser the console.log
result of the element.
We can see the React element which is also a JS object unlike the HTML elements.
We can also create the same element using JSX in React. This time while working on the React project we don't have to include babel manually because babel is already included in the React project.
const element = <h1>Hello World!</h1>;
console.log(element);
This will provide the same result as the React.createElement
.
We can show dynamic values to JSX using curly braces.
const element = <h1>Hello {name}!</h1>;
We can also use any valid JS expressions in JSX
const element = <h1>Hello {firstname + lastname}!</h1>;
JSX itself is a valid JS expression. We can return JSX expression in a function.
function getGreeting(user) {
if (user) {
return (
<h1 className="heading">
<span>Hello, {user}!</span>
</h1>
)
} else {
return <h1>Hello, user!</h1>
}
}
console.log(getGreeting('rabib'));
We can also call the function inside the element.
function getGreeting(user) {
if (user) {
return (
<span>{user}!</span>
)
} else {
return <span>user!</span>;
}
}
const element = <h1>Hello {getGreeting('rabib')}</h1>
console.log(element);
This is called Interpolation
.
Now let's get some idea about Attributes in JSX
JSX attributes are not the same as HTML attributes.
JSX turns into JavaScript and attributes written in JSX become keys of JavaScript objects.
JavaScript has limitations on variable names. For example, their names can't containdashes
or be reserved words likeclass
.
That is why in JSX attributes are mostly written in camelCase. For example we use className
instead of class
in JSX. Let's check the below element.
const element = (
<h1 className="heading">
<span className="text">Hello {new Date().toLocaleTimeString()}</span>
<img src="" className="img-fluid"/>
</h1>
);
console.log(element);
To create multiline element we use first bracket
()
to wrap the element contents. Otherwise if there there is a semicolon;
inside the element before ending, then JS expression will alredy set before ending the element. Which could create issues.
Here we are using className
attribute which is added to React element object as props
property element. Let's see in the console.
Also we can see from the console that by creating child elements inside the h1
tag we are creating child objects inside the React element object.
There are two child object elements for text
and image
and these are added as array elements inside the props
of the parent object element h1
.
Preventing malicious attack in React
To prevent any malicious attack React automatically escape the values inside the
{}
So from now we might get the idea what React Element is. React element is the smallest building block of React.
Now let's print our React element in the browser. We will use ReactDOM
library to render the React element in the browser.
We can see in our React project there is a index.html
file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
We will render inside the root
div.
let index = 0;
const element = (
<h1 className="heading" tabIndex={index}>
<span className="text">Hello {new Date().toLocaleTimeString()}</span>
<img src="" />
</h1>
);
ReactDOM.createRoot(document.getElementById('root')).render(element);
We can see in the browser that the created element is shown.
Now let's update the time in each interval.
let index = 0;
const root = ReactDOM.createRoot(document.getElementById('root'));
setInterval(() => {
const element = (
<h1 className="heading" tabIndex={index}>
<span className="text">Hello {new Date().toLocaleTimeString()}</span>
<img src="" />
</h1>
);
root.render(element);
}, 1000);
We can see from the above example that, only time
is updating in the DOM. But inside the React virtual DOM the element is created each time. And react only updating the DOM after comparing the states inside the virtual DOM. Amazing! isn't it?
Normally, we will never create the element multiple times but we will change the data and based on the component we will update the UI based on the date change.
I will learn about how to create and use the component and share in my next post. 😊
I found it really helpful going through Writing Markup with JSX post from React official Documentation while learning JSX.
I have started posting about my learning for the last few days. Here are the previous posts about React.
- Installing React with Vite
- Learning React: Virtual DOM
- Learning React : about JSX
- At last I am learning React: Day 1
Thank you for reading. Bye 👋
Top comments (0)