Skip to content

JSX

beginner2 min read
  • React
  • JavaScript

The syntax that lets you write markup directly inside JavaScript, embedding dynamic values with curly braces so UI and logic live together.

Prerequisites

  • React components (see Related Topics)

What you'll understand

  • What JSX is and why React uses it
  • How to embed dynamic values in markup
  • The small ways JSX differs from HTML

Explanation

JSX is a syntax extension that lets you write markup that looks like HTML directly inside your JavaScript. It is what a component returns. JSX exists because in React, rendering logic and markup belong together: the same component that decides what to show also describes how it looks, and JSX lets both live in one place.

The feature that makes JSX dynamic is the curly brace. Anywhere inside JSX you can write { } to drop in a JavaScript expression, a variable, a calculation, a function call, and its value is rendered. This is the bridge between your data and your markup: text, attributes, and values all come from ordinary JavaScript expressions embedded in the JSX.

JSX looks like HTML but is not identical. Because it is JavaScript, some attribute names differ to avoid reserved words, most notably class becomes className. Every element must be closed, including self-closing ones like <img />, and a component must return a single root element (you can wrap siblings in a fragment). These small differences trip up beginners but quickly become second nature.

Examples

Curly braces embed JavaScript expressions into the markup:

function Greeting() {
  const name = 'Ada';
  return <h1>Hello, {name}!</h1>;
}

Attributes use JavaScript names like className, and siblings are wrapped in a single root:

<div className="card">
  <img src={avatarUrl} alt="avatar" />
  <p>{bio}</p>
</div>

Common mistakes

  • Using class instead of className for CSS classes.
  • Returning multiple sibling elements without a wrapping element or fragment.
  • Forgetting to close elements, including self-closing tags like <br />.
  • Trying to put a statement (like an if) inside curly braces, which only accept expressions.

Best practices

  • Use curly braces to render dynamic values from JavaScript.
  • Wrap multiple elements in a fragment to keep a single root.
  • Remember the HTML-to-JSX differences such as className.
  • Keep expressions in JSX small; move complex logic above the return.

Further reading

Related topics