JSX in React

What is JSX?

It is a syntax extension for JavaScript that allows you to write HTML-like code inside JavaScript files.


Why use JSX?

JSX makes it easier and cleaner to create React elements and build the UI.

  1. Without JSX: HTML and JavaScript are written separately.
  2. With JSX: You can write both together in the same file.


Example with JSX:

function App() {
const userName = "Anil Sidhu";
let x = 20;
let y = 30;

return (
<div>
<h1>{userName}</h1>
<h1>{10 + 20 + 30}</h1>
<h1>{x * y}</h1>
<button onClick={() => alert("Hello")}>Click</button>
</div>
);
}


Here:

  1. {userName} is JavaScript inside JSX.
  2. {10 + 20 + 30} and {x * y} are also JS expressions.
  3. The onClick event is handled using an arrow function.


Without JSX (Old React method):


import { createElement } from "react";

function App() {
return createElement(
"div",
{ id: "rootDiv" },
createElement("h1", { className: "heading" }, "Hello without JSX")
);
}

This is harder to read and write, which is why JSX is preferred.


JSX Full Form

There’s often some confusion about what JSX stands for. Some say it means JavaScript Extension, while others believe it's JavaScript XML. However, there is no official full form of JSX mentioned on the React official website — it’s just a syntax extension used to write HTML-like code in JavaScript.