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 why it’s important for building dynamic user interfaces in web development.

Let’s explore this revolutionary technology in more detail.

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).

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?

JSX is transformed into regular JavaScript before it is executed in the browser. This transformation is done using a tool called a transpiler. The most popular transpiler for JSX is Babel.

Babel transforms the JSX code into a series of function calls. These function calls are equivalent to the HTML-like code written in JSX. The browser can then execute the resulting JavaScript code.

For example, the following JSX code:

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

is transformed into the following JavaScript code:

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

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 these components in a single file.

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

import React from 'react';

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

export default Greeting;

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

The React compiler will transform this code into optimized JavaScript code that can be executed by the browser, allowing the component to be rendered on the screen.

Here’s what the React compiler would transform the Greet component into:

import React from 'react'

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

In this code, the JSX code has been transformed into a React.createElement call that creates the same structure and content as the original JSX code.

This is what happens behind the scenes when React compiles JSX code, allowing it to be executed by the browser. However, the transformed code may be less readable than the original JSX code.

In React version 17, a new JSX transform feature was introduced, which automatically imports special functions from the React package’s new entry points allowing developers to use JSX without having to import React at the top of their files.

// Inserted by a compiler (don't import it yourself!)
import {jsx as _jsx} from 'react/jsx-runtime';

function App() {
  return _jsx('h1', { children: 'Hello world' });
}

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 JSX components.

This example shows how to use two JavaScript expressions within JSX:

import React from 'react';

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 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, or CSS-in-JS libraries. Inline styles are defined directly within the JSX markup using JavaScript objects, while separate CSS files or CSS-in-JS libraries allow for external and modular styling of components.

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

import React from 'react';

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, and their values are strings representing the CSS values.

Note: While inline styles provide flexibility and simplicity, it’s recommended to use CSS classes or CSS-in-JS libraries for more complex or reusable styles in larger applications.

6 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, you must always 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>
)

This is important to bear in mind when converting HTML codes 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>

Using className instead of class is important and avoids naming conflicts because class is a reserved keyword in JavaScript.

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>

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

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

Also, within your curly braces, you can set up conditional statements using ternary operators:

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

Here is a better example with 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.”.

4. Use camelCase for Most Things In JSX

In JSX, use camelCase for most things, including attributes, event handlers, and variable names. This convention is consistent with JavaScript naming conventions and helps maintain readability.

For example, use onClick instead of onclick, and className instead of class.

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

// Bad
<button onclick={handle_click} class="btn">Click me!</button>

5. Always Close Tags

In JSX, you need to always close your tags, even if they don’t have any content. For example:

// Good
<div></div>

// Bad
<div/>

6. Use Self-Closing Tags for Empty Elements

If you have an element that doesn’t have any content, you can use a self-closing tag instead of an opening and closing tag. For example:

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

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

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.
  1. 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.
  1. 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.
  1. 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 some rules to follow when using JSX — by following these rules, we can write clean, readable, and maintainable code that is consistent with JavaScript naming conventions.