React - JSX Basics

What is JSX?

JSX lets you write HTML-like syntax in JavaScript. It compiles to React.createElement calls.

Key Rules

  • Use className, not class.
  • One root element per component (use fragments <>...</> if needed).
  • JavaScript expressions go in {...}.

Try it

View source
function App(){
  const user = { first: 'Ada', last: 'Lovelace' };
  const items = ['JSX', 'Props', 'State'];
  return (
    <>
      <h3 className="title">Welcome, {user.first} {user.last}!</h3>
      <p>Today we'll learn:</p>
      <ul>
        {items.map((x, i) => <li key={i}>{x}</li>)}
      </ul>
    </>
  );
}
ReactDOM.createRoot(document.getElementById('try-jsx')).render(<App />);

Syntax primer (for newcomers)

  • className instead of class in JSX.
  • Wrap JavaScript inside {...}, e.g., {user.first}.
  • One root element per component; use fragments <>...</> for grouping without extra DOM nodes.

Vocabulary

  • JSX: HTML-like syntax in JavaScript that compiles to React elements.
  • Fragment: <>...</> wrapper that doesn’t render an extra DOM node.

More examples

Inline styles and conditional classes:

View source
function StyleDemo(){
  const danger = true;
  const box = { padding: 10, borderRadius: 6, border: '1px solid #1f2937' };
  return (
    <div style={box} className={danger ? 'is-danger' : 'is-ok'}>
      Status: {danger ? 'Danger' : 'OK'}
    </div>
  );
}
ReactDOM.createRoot(document.getElementById('try-jsx-2')).render(<StyleDemo />);

Common pitfalls

  • Attributes are camelCased (e.g., onClick, tabIndex).
  • Use style={{ key: 'value' }} with a JavaScript object, not a string like HTML.
  • Lists need key props; avoid using array indexes when items can reorder.

Exercises

  1. Refactor the fragment shorthand <> to <React.Fragment> and verify it renders the same.
  2. Add a danger boolean and conditionally apply a class; show both states.
  3. Render a list of objects with stable key values (e.g., id) instead of using indexes.