Topic 02 / 14

JSX — JavaScript + Markup

~9 min read  //  React Series  //  Coding India

JSX Is JavaScript

JSX looks like HTML but compiles to function calls — <h1>Hi</h1> becomes createElement("h1", null, "Hi"). Because it’s JavaScript, you can embed any expression with braces:

function Profile() {
  const user = { name: "Ravi", score: 82 };
  return (
    <div>
      <h2>{user.name}</h2>
      <p>Score: {user.score} ({user.score >= 60 ? "pass" : "fail"})</p>
      <p>Doubled: {user.score * 2}</p>
    </div>
  );
}

Braces take expressions (things that produce a value) — not statements. No if or for inside braces; use ternaries and map() instead (next topics).

The Differences From HTML

<div className="card">            // class → className
<label htmlFor="email">           // for → htmlFor
<img src={logo} alt="Logo" />     // every tag must close — note the /
<input disabled={isLocked} />     // attributes take {expressions}
<div style={{ color: "red", fontSize: "1rem" }}>  // style = object, camelCase

Attribute names are camelCase: onClick, tabIndex, autoComplete.

One Root Element — Use Fragments

A component must return a single element. When you don’t want a wrapper div, use a fragment:

function Row() {
  return (
    <>
      <td>Django</td>
      <td>₹199</td>
    </>
  );
}

Composing Components

Components render other components — this is the whole game:

function Header() {
  return <header><h1>Coding India</h1></header>;
}

function App() {
  return (
    <>
      <Header />
      <main>...</main>
    </>
  );
}

JSX Is Auto-Escaped

Like Django templates, anything in braces renders as text, not HTML — XSS is blocked by default:

const userInput = "<script>alert('hack')</script>";
<p>{userInput}</p>     // renders the literal text, harmless

Comments & Whitespace

<div>
  {/* comments inside JSX look like this */}
  <p>Hello</p>
</div>

Mental shift to make now: in React you’ll write markup inside JS, organised by component, not by file type. A component owns its markup, logic, and (often) styles together — cohesion beats separation of file extensions.