Understanding JSX & Components in Depth

March 21, 2025
Deepak Maurya
2 min read

What is JSX?

JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code inside JavaScript. React uses JSX to define UI components in a more readable and declarative way.

JSX Example

const heading = <h1>Hello, React!</h1>;
console.log(heading);

Even though it looks like HTML, JSX is not HTML. It gets converted into plain JavaScript by Babel (a JavaScript compiler). The above JSX code translates into:

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

Why JSX

  • More Readable: It makes the UI code easier to understand.
  • Prevents Cross-Site Scripting (XSS) Attacks: JSX escapes all inputs to avoid injection attacks.
  • Better Debugging: JSX provides better error messages than plain JavaScript.

JSX Rules & Best Practices

Rule 1: JSX must have a single parent element

Correct

return (
  <div>
    <h1>Hello</h1>
    <p>Welcome to React!</p>
  </div>
);

Incorrect

return (
    <h1>Hello</h1>
    <p>Welcome to React!</p>
);

Solution

Use a fragment (<>...</>) when you don't want extra div s.

return (
    <>
    <h1>Hello</h1>
    <p>Welcome to React!</p>
  </>
);

Rule 2: Use className Instead of class

JSX uses className because class is a reserved keyword in JavaScript.

const Button = () => {
  return <button className="btn">Click Me</button>;
};

Rule 3: JSX Expressions Must Be Inside {}

Correct

const name = "Deepak";
return <h1>Hello, {name}!</h1>;

Incorrect

return <h1>Hello, name!</h1>;  // Won't work