Agentic hosting is here. Connect to our MCP now ->

Blog

The uncomplicated guide to JSX syntax

JSX looks like HTML, but it's JavaScript: every tag you write becomes a function call before the browser ever sees it.

ยทby Joel Olawanle

Traditionally, developers have separated markup and logic into separate files, using HTML for structure and CSS for styling and then writing JavaScript to handle interactions and data manipulation.

But what if there was a way to combine these technologies, simplifying the development process and making it easier to build complex user interfaces? That's where JSX comes in.

In this article, you'll learn what JSX is, how it works, and the rules you need to follow to write it correctly. The examples were tested with React 19 and Babel.

What is JSX?

JSX (JavaScript XML) is a syntax extension for JavaScript that allows developers to write HTML-like code inside a JavaScript file. It was developed by Meta (formerly Facebook) for React, and other libraries, such as Preact and Solid, use it too.

The syntax of JSX resembles HTML, with opening and closing tags, attributes, and nested elements.

For example, you might write the following JSX code to render a simple heading element:

const heading = <h1>Hello, JSX!</h1>;

This code looks like HTML, but it's JavaScript. The const keyword creates a new variable named heading, and the value of that variable is the result of the JSX expression.

How does JSX work?

Browsers don't understand JSX, so it's transformed into regular JavaScript before it runs in the browser. JSX looks like HTML, but it's JavaScript: every tag you write becomes a function call before the browser ever sees it.

This transformation is done by a compiler, such as Babel, TypeScript, esbuild, SWC, or Oxc. In practice, you rarely run it yourself: build tools like Vite and frameworks like Next.js transform JSX for you.

For example, the following JSX code:

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

was traditionally transformed into this JavaScript code:

const element = React.createElement("h1", null, "Hello, world!");

The first argument is the element type, the second holds the attributes, called props (null here, since there are none), and the rest are the children. React.createElement() returns a plain JavaScript object that describes the element, which React then uses to update the page.

This transformation allows developers to write code in a syntax that is familiar and easy to read, while still taking advantage of the power and flexibility of JavaScript.

JSX and React

JSX is an integral part of React, allowing developers to write the markup and logic for their components in a single file.

Here's a simple example of JSX code in a React component:

function Greet() {
  return <h1>Hello, World!</h1>;
}
 
export default Greet;

In this example, you have a function component named Greet that renders an h1 element with a greeting message.

With the classic JSX transform, Babel turns the component into this:

function Greet() {
  return React.createElement("h1", null, "Hello, World!");
}

The JSX has been transformed into a React.createElement() call that creates the same structure and content as the original JSX code. That's also why, in older React code, every file that used JSX had to start with import React from 'react'.

React 17 introduced a new JSX transform, which is now the default. Instead of calling React.createElement(), the compiler automatically imports special functions from React's react/jsx-runtime entry point. The same component becomes:

// Inserted by the compiler (don't import it yourself!)
import { jsx as _jsx } from "react/jsx-runtime";
 
function Greet() {
  return _jsx("h1", { children: "Hello, World!" });
}

With the new transform, you no longer need to import React at the top of your files to use JSX, so the examples in this article don't.

Using JavaScript expressions with JSX

In JSX, JavaScript expressions can be embedded directly within the markup to generate content dynamically. This allows developers to use JavaScript code to compute values, perform operations, and conditionally render content within their components.

This example shows how to use JavaScript expressions within JSX:

const MyComponent = () => {
  const name = 'John';
  const age = 30;
 
  return (
    <div>
      <h1>Hello, {name}!</h1>
      <p>You are {age} years old.</p>
      <p>Next year, you will be {age + 1} years old.</p>
      {age >= 18 && <p>You are an adult.</p>}
    </div>
  );
};
 
export default MyComponent;

In this example, JavaScript expressions like {name}, {age}, {age + 1}, and {age >= 18 && <p>You are an adult.</p>} are used to dynamically render content based on the values of the name and age variables.

Using CSS with JSX

CSS can be applied to JSX components in various ways, such as inline styles, separate CSS files, CSS Modules, or CSS-in-JS libraries. Inline styles are defined directly within the JSX markup using JavaScript objects, while the other options keep your styles in separate, reusable files or modules.

This example shows how to apply inline styles defined using a JavaScript object to elements using the style attribute in JSX:

const MyComponent = () => {
  const styles = {
    backgroundColor: 'blue',
    color: 'white',
    padding: '10px'
  };
 
  return (
    <div style={styles}>
      <h1>Hello, World!</h1>
      <p>This is a component with inline styles.</p>
    </div>
  );
};
 
export default MyComponent;

In this example, CSS properties like backgroundColor, color, and padding are set as key-value pairs in the styles object. Property names use camelCase, such as backgroundColor instead of background-color, and their values are strings representing the CSS values.

While inline styles provide flexibility and simplicity, it's recommended to use CSS classes for more complex or reusable styles in larger applications.

5 important JSX rules

When writing JSX code, there are certain rules you should follow to ensure it's valid and easy to read.

1. Always return a single root element

In JSX, a component must return a single root element. This means all your JSX code must be contained within a single outermost element. For example, this is valid JSX:

return (
  <div>
    <h1>Hello World!</h1>
    <p>This is my first React component.</p>
  </div>
);

But this is not, because it returns two elements instead of one:

return (
  <h1>Hello World!</h1>
  <p>This is my first React component.</p>
);

The compiler stops with an error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...</>?

If you don't want to add an extra div to the page, wrap the elements in a fragment, <>...</>, which groups them without adding an element to the DOM:

return (
  <>
    <h1>Hello World!</h1>
    <p>This is my first React component.</p>
  </>
);

This is important to bear in mind when converting HTML code to JSX.

2. Use className instead of class

In HTML, you would use the class attribute to specify a CSS class for an element. However, in JSX, you need to use the className attribute instead. For example:

// Good
<div className="my-class">This element has a CSS class.</div>
 
// Bad
<div class="my-class">This element has a CSS class.</div>

JSX uses className because class is a reserved keyword in JavaScript, and JSX attributes follow the names of DOM properties. If you use class, React 19 still applies the class, but it logs a warning in development: Invalid DOM property 'class'. Did you mean 'className'?

The same applies to the for attribute of labels, which is htmlFor in JSX.

3. Use curly braces for JavaScript expressions

When you need to include a JavaScript expression inside your JSX code, you need to wrap it in curly braces, {}. This can be used for anything from displaying dynamic data to conditionally rendering components. Here's an example:

// Good
<div>{myVariable}</div>
 
// Bad
<div>myVariable</div>

Without the curly braces, JSX treats myVariable as plain text and displays the word "myVariable" instead of the variable's value.

You can also execute mathematical operations within the curly braces, such as:

<p>The total cost is {25 * 10}</p>

Within your curly braces, you can also render content conditionally with the ternary operator:

<h1>{x < 15 ? "Welcome" : "Goodbye"}</h1>

Here is a better example with a React component:

function Greeting() {
  const isLoggedIn = true;
 
  return (
    <div>
      {isLoggedIn ? (
        <h1>Welcome back!</h1>
      ) : (
        <h1>Please log in.</h1>
      )}
    </div>
  );
}

In this example, we define a Greeting component. The component uses the ternary operator to conditionally render a greeting based on the value of isLoggedIn. If isLoggedIn is true, the component renders an h1 element with the text "Welcome back!". If isLoggedIn is false, the component renders an h1 element with the text "Please log in."

Note that curly braces accept expressions, not statements, so you can't use if statements or for loops directly inside JSX. Use the ternary operator, &&, or methods like map() instead, or put the logic before the return statement.

4. Use camelCase for most things in JSX

In JSX, use camelCase for attribute names and event handlers. This convention matches the names of JavaScript DOM properties and keeps your code consistent.

For example, use onClick instead of onclick, and tabIndex instead of tabindex:

// Good
<button onClick={handleClick} className="btn">Click me!</button>
 
// Bad
<button onclick={handleClick} class="btn">Click me!</button>

This matters more than it seems: React ignores the lowercase onclick prop, so your click handler never runs, and logs a warning in development instead. The exceptions are aria-* and data-* attributes, which keep their dashes, like in HTML.

5. Close every tag

In JSX, every element must be closed. In HTML, some elements, such as img, input, and br, don't need a closing tag, but in JSX, leaving one open is an error:

// Bad
<img src="my-image.jpg" alt="My Image">

You can close an element in two ways: with a closing tag, or, if it has no children, by making it self-closing with />. Both are valid for any element:

// Good
<img src="my-image.jpg" alt="My Image" />
<div></div>
<div />

The common convention is to use self-closing tags for elements without children, such as <img />, <input />, and <br />, because they're shorter and easier to read.

Why is JSX important for web development?

JSX is important for web development because:

  1. It allows developers to build user interfaces in a more intuitive and familiar way.
  2. Instead of manipulating the DOM directly, developers can use JSX to describe the structure of their user interface in a way that is more like writing HTML.
  3. It allows for more efficient and flexible development. Because JSX is just JavaScript, developers can take advantage of all the features of JavaScript to create more complex and dynamic user interfaces.
  4. It is an important part of the React library, which is one of the most popular choices for building user interfaces in modern web development. If you want to use React, you will need to learn JSX.

Summary

JSX is a syntax extension for JavaScript that allows developers to write HTML-like markup inside a JavaScript file. This makes creating dynamic and interactive user interfaces for web applications easier.

You've learned how JSX is transformed into JavaScript, and the rules to follow when you write it. By following these rules, you can write clean, readable, and maintainable code that is consistent with JavaScript naming conventions.

When your React app is ready, you can deploy it for free with Sevalla's Static Site Hosting.

Deep dive into the cloud!

Deploy your application, database, or static site in minutes.