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?! 🀘

Top comments (2)

Collapse
 
lukeshiru profile image
Luke Shiru

Hi Fahim! This might be like a weird question, but might I ask what inspired you to make this post about JSX? Do you follow an influencer on Twitter or YouTube, or do you maybe received a newsletter about it? I'm mainly asking because yours is literally the third "What is JSX" kind of post I seen in the last 15 minutes, and I'm wondering if is just a coincidence or if folks are getting "influenced" by something.

Collapse
 
fahimshahriar profile image
Fahim Shahriar

maybe coincidence ! :o

πŸ” If you came here from Google, why not take a look at some of our top posts?