AtomLearn
DashboardGoalsGraphAchievementsReviewSign In
ReactNot Started

JSX

HTML-like syntax in JavaScript — what JSX is and how it compiles

0%

Knowledge Debt detected

You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.

Explanation

JSX is a syntax extension that lets you write HTML-like markup inside JavaScript. Babel compiles it to React.createElement() calls.

jsx
// JSX
const el = <h1 className="title">Hello</h1>;

// What it compiles to const el = React.createElement('h1', { className: 'title' }, 'Hello'); ```

Key JSX rules:

1. Return a single root element — wrap in a fragment if needed: ``jsx return ( <> <h1>Title</h1> <p>Body</p> </> );

  1. 1Close all tags<br />, <img />, <input />

3. className, not classclass is a reserved JS keyword: ``jsx <div className="card">

4. htmlFor, not for — on labels: ``jsx <label htmlFor="email">Email</label>

5. Expressions in curly braces: ``jsx const name = 'Alice'; <h1>Hello, {name}!</h1> <p>{2 + 2}</p> <p>{isLoggedIn ? 'Welcome' : 'Please sign in'}</p>

6. JS objects for inline styles: ``jsx <div style={{ color: 'red', fontSize: 16 }}>

Examples

JSX with expressions

Curly braces let you embed any JS expression in JSX

function UserCard({ name, age, active }) {
  return (
    <div className="card">
      <h2>{name}</h2>
      <p>Age: {age}</p>
      <span className={active ? 'badge-green' : 'badge-grey'}>
        {active ? 'Online' : 'Offline'}
      </span>
    </div>
  );
}

Fragment avoids extra DOM wrapper

<> </> is shorthand for React.Fragment — renders no DOM element

function TableRow({ name, score }) {
  return (
    <>
      <td>{name}</td>
      <td>{score}</td>
    </>
  );
  // Without fragment we'd need a <div> which would break table structure
}

Next in React

Components & Props

Continue