JSX: Markup Inside JavaScript

A component is a function that returns JSX. See plain JavaScript values flow into the markup through curly braces.

React · beginner · 6 min · 7 steps · free

What you'll learn

JsxBasics.jsx

export default function Profile() {
  const name = 'Ada Lovelace';
  const born = 1815;
  const years = 2026 - born;
  const titleStyle = { color: 'purple', fontSize: 24 };

  return (
    <div className="profile">
      <h2 style={titleStyle}>{name}</h2>
      <p>Born in {born}, {years} years ago.</p>
      <p>{name.length > 10 ? 'A long name' : 'A short name'}</p>
    </div>
  );
}

Step by step

  1. React calls Profile. A component is just a function: React calls it to find out what the screen should show.
  2. name = "Ada Lovelace".
  3. born = 1815.
  4. Ordinary JavaScript runs inside a component: years = 2026 − 1815 = 211.
  5. A style in JSX is a JavaScript object, with names in camelCase: fontSize, not font-size.
  6. Profile returns JSX. It looks like HTML, but it is JavaScript: {name} puts the value of name into the markup. Nothing is on the page yet.
  7. React creates the real elements: look at the Screen panel. className became class, and the style object became CSS.

Common mistakes

Best practices

Key takeaways

Check yourself

What does {2 + 3} show in JSX?

Answer: 5. The expression is worked out first.

Which attribute sets a CSS class in JSX?

Answer: className. class is a reserved word in JavaScript.

More in Components and JSX