devnotes.

JSX: Syntax & Rules

JSX (JavaScript XML) is a syntax extension that lets you write HTML-like markup inside JavaScript. It is not required to use React, but it is the standard way almost everyone writes it. Under the hood, a build tool (Babel/Vite) compiles JSX into plain React.createElement() calls.

const element = <h1>Hello, world!</h1>;

// compiles roughly to:
const element = React.createElement('h1', null, 'Hello, world!');

Embedding JavaScript expressions

Anything inside curly braces {} is evaluated as a JavaScript expression:

const name = 'Rahim';
const element = <h1>Hello, {name}!</h1>;
const sum = <p>2 + 2 = {2 + 2}</p>;

JSX rules that differ from HTML

  1. One root element — wrap sibling elements in a parent, or use a Fragment.
function Profile() {
  return (
    <>
      <h2>Rahim Uddin</h2>
      <p>Software Engineer</p>
    </>
  );
}
  1. className instead of class, htmlFor instead of for — because class and for are reserved words in JavaScript.
<label htmlFor="email" className="form-label">Email</label>
  1. camelCase attributes — onClick, tabIndex, strokeWidth, not onclick, tabindex.

  2. Every tag must be closed — <img />, <br />, <input /> are self-closing.

  3. Inline styles are objects, not strings, and property names are camelCase:

<div style={{ backgroundColor: 'tomato', fontSize: 20 }}>Styled</div>
  1. Comments need curly braces:
{/* this is a JSX comment */}

Conditional rendering inside JSX

function Greeting({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn ? <p>Welcome back!</p> : <p>Please sign in.</p>}
      {isLoggedIn && <button>Log out</button>}
    </div>
  );
}
JSX Syntax in React Explained with Examples | DevNotes