Sikau

React · Day 2 · about 25 min

JSX rules

HTML-like markup with JavaScript inside.

Almost HTML

JSX looks like HTML, but it's JavaScript underneath. That means a few rules differ — and it means you can drop any JavaScript value into the markup with { }.

Curly braces and the rules

const dish = "Momo";
const price = 180;
const imgUrl = "https://picsum.photos/120";

export default function Dish() {
  return (
    <div className="card">
      <h2>{dish.toUpperCase()}</h2>
      <p>Price: Rs {price * 2} for two plates</p>
      <img src={imgUrl} alt={dish} />
      <label htmlFor="qty">Quantity</label>
      <input id="qty" />
    </div>
  );
}
  • Return one root element. Need two side by side? Wrap them in a fragment: <>…</>.
  • Close every tag: <br />, <input />.
  • Attributes are camelCase: onClick, tabIndex, className.
  • Inline styles take an object: style={{ color: "red", fontSize: 20 }}.
  • { } takes expressions, not statements — use a ternary instead of if.

The rest of this lesson

  • What JSX becomesexplain
  • Expressions inside bracesexplain
  • What shows?predict
  • Fix the JSXfill
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 24 lessons of React