JSX
Fahim Shahriar
Posted on December 22, 2021
JSX - JavaScript XML. It is simply a syntax extension of JS. It allows us to write HTML and JavaScript code together.
Example:
const name = "Fahim Shahriar";
<h1>Today our special guest is {name} </h1>
As simple as that! π
Concept: Suppose we want to render a HTML element - h1. We write our HTML code like: <h1>Hello world!</h1>
. Then we see a heading in our browser. But under the hood browser takes the element in it's DOM and create element in another way.
Example:
let h1 = document.createElement("h1");
h1.innerHTML = "Hello World";
domContainer.appendChild(h1);
We write these code in HTML like: <h1>Hello World</h1>
. HTML syntax made it easy for us.
React is working in the same way. It creates element KINDA same way and creates a separate DOM called virtual DOM.
We creates HTML element with HTML syntax and React provides JSX syntax for create React elements.
For understand the JSX file, JS uses Transpiler. Ex: Babel. Behind the scene Babel transpiles this JSX syntax in vanilla javascript.
JSX Expression:
JSX supports expression in pure JavaScript syntax. A JSX expression starts with an HTML-like open tag and ends with the corresponding closing tag. JSX tags support the XML self-close syntax so we can optionally leave the closing tag off. JSX expressions evaluate to ReactElements.
Another JSX code example:
suppose you have an array. And you want to render as a list item on your webpage. You can do it in a supercool way with jsx.
import React from "react";
const nameList = [ "Tom", "John", "Clerk", "Harry"]
const app = () {
return (
<ul>
{
nameList.map(name => <li>{name}</li>)
}
</ul>
);
Isn't it super cool?! π€
Posted on December 22, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.