DEV Community

Fahim Shahriar
Fahim Shahriar

Posted on

JSX

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>
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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>
);
Enter fullscreen mode Exit fullscreen mode

Isn't it super cool?! 🤘

Latest comments (1)

Collapse
 
fahimshahriar profile image
Fahim Shahriar

maybe coincidence ! :o