Understanding JSX
A syntax extension for JavaScript, commonly used with React.

JSX (JavaScript XML) is a syntax extension that looks a lot like HTML or XML, and it's used with React to describe what the UI should look like. While you don't have to use JSX with React, it's a helpful tool that makes writing React applications easier and more intuitive.

Consider this variable declaration:

const element = <h1>Hello, world!</h1>;

This funny tag syntax is neither a string nor HTML. It is JSX, and it is a syntax extension to JavaScript. React recommends using it to describe what your UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript.

Embedding Expressions in JSX

You can embed any JavaScript expression in JSX by wrapping it in curly braces. For example, `2 + 2`, `user.firstName`, or `formatName(user)` are all valid JavaScript expressions.

function formatName(user) {
  return user.firstName + ' ' + user.lastName;
}

const user = {
  firstName: 'Harper',
  lastName: 'Perez'
};

const element = (
  <h1>
    Hello, {formatName(user)}! {/* JavaScript expression in curly braces */}
  </h1>
);

JSX also gets compiled down to `React.createElement()` calls, which is what React actually uses to create elements.

Test Your Knowledge

What does JSX stand for?

Why is JSX used in React?

How do you embed a JavaScript expression within JSX?