What is JSX

Anu MauAnu Mau
2 min read

What is JSX

JSX is acronyms of java script XML(extensible markup language).

Without JSX (Using React.createElement)

import React from "react";

const MyComponent = () => {
  return React.createElement(
    "div",
    null,
    React.createElement("h1", null, "Hello, Anubhav!"),
    React.createElement("p", null, "This is a React component without JSX.")
  );
};

export default MyComponent;

Explanation:

  • React.createElement(type, props, ...children) is used to create elements.

  • "div" is the element type.

  • null represents no additional props.

  • React.createElement("h1", null, "Hello, Anubhav!") creates an <h1> inside <div>.

  • More verbose and harder to read than JSX.

With JSX (Easier and More Readable)

import React from "react";

const MyComponent = () => {
  return (
    <div>
      <h1>Hello, Anubhav!</h1>
      <p>This is a React component using JSX.</p>
    </div>
  );
};

export default MyComponent;

How React Translates JSX into JavaScript

1. Writing JSX Code

2. Babel Transpiles JSX into JavaScript

const element = React.createElement("h1", null, "Hello, Anubhav!");

example 2: 

const element = <h1 id="title">Hello, Anubhav!</h1>;
React.createElement(type, props, ...children);

example 2:

const element = React.createElement("h1", { id: "title" }, "Hello, Anubhav!");
  • type: The type of the element (e.g., "h1", "div", "span", or a React component).

  • props: The properties or attributes of the element (e.g., className, id, onClick).

...children: The inner content of the element.

4. React.createElement() Converts to Virtual DOM

{
  type: "h1",
  props: {
    id: "title",
    children: "Hello, Anubhav!"
  }
}

5. ReactDOM Renders Virtual DOM into Real DOM

import React from "react";
import ReactDOM from "react-dom/client";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<h1>Hello, Anubhav!</h1>);
0
Subscribe to my newsletter

Read articles from Anu Mau directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Anu Mau
Anu Mau