JSX — HTML in JavaScript

JSX is a syntax extension that lets you write HTML-like code inside JavaScript. It looks like HTML but it's really JavaScript — the compiler turns it into function calls.

Basic JSX

JSX
function Greeting() {
  return (
    <div>
      <h1>Hello, world!</h1>
      <p>This is JSX, not HTML.</p>
    </div>
  );
}

Expressions in curly braces

JSX
function Profile({ name, age }) {
  return (
    <div>
      <h1>{name}</h1>
      <p>Age: {age}</p>
      <p>In 5 years: {age + 5}</p>
      <p>{1 + 1 === 2 ? 'Math works!' : 'Something is wrong'}</p>
    </div>
  );
}

Any JavaScript expression works inside {} — function calls, ternaries, arithmetic, array methods.

JSX rules

JSX
// ✅ One root element (use a fragment if needed)
function App() {
  return (
    <>
      <h1>Title</h1>
      <p>Content</p>
    </>
  );
}

// ✅ className instead of class
<div className="card">Card</div>

// ✅ camelCase for attributes
<button onClick={handleClick}>Click</button>
<input onChange={handleChange} />
<label htmlFor="name">Name</label>

// ✅ Self-closing tags for empty elements
<img src="photo.jpg" />
<input type="text" />
<br />

Conditional rendering

JSX
function Greeting({ isLoggedIn, name }) {
  if (!isLoggedIn) return <p>Please log in.</p>;

  return <h1>Welcome, {name}!</h1>;
}

// Inline ternary
<div>
  {isLoggedIn ? <h1>Welcome!</h1> : <p>Please log in.</p>}
</div>

// Short-circuit (&&)
<div>
  {items.length > 0 && <ItemList items={items} />}
</div>

JSX is just JavaScript

JSX
// This JSX:
<h1 className="title">Hello</h1>

// Compiles to this JavaScript:
React.createElement('h1', { className: 'title' }, 'Hello');

Tips

  • JSX is not HTML — use className, htmlFor, camelCase event handlers.
  • Every component must return one root element (use <> fragments).
  • Curly braces {} let you embed any JavaScript expression.
  • JSX makes your component's structure immediately visible.

Next: components.