Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is React JSX?

Introduction

React is a popular JavaScript library for building user interfaces. It allows developers to create reusable components that can be easily manipulated and rendered on a web page. One of the unique features of React is JSX. In this article, we will learn what JSX is, how it works, and how to use it in a React application. We will also see some code examples to better understand its usage.

What is JSX?

JSX stands for JavaScript XML. It is a syntax extension for JavaScript that allows you to write HTML-like code within your JavaScript code. JSX is not a new language or a templating engine but a way to write markup and code together within a single file. Think of it as a way to mix JavaScript and HTML together in a more natural and intuitive way.

One thing to note is that JSX is not natively understood by web browsers. It needs to be compiled down to plain JavaScript in order to work. Luckily, this is done automatically when you use tools like Babel, which is commonly used with React.

Why JSX?

You might be wondering why we need JSX when we can use JavaScript to create and manipulate HTML elements. The answer lies in the readability and ease of use that JSX brings to the table. JSX allows you to write more concise and cleaner code, making it easier to understand and maintain.

Let's compare creating an element using JavaScript and JSX.

JavaScript

const element = document.createElement("h1");
element.textContent = "Hello, World!";
element.className = "greeting";

JSX

const element = <h1 className="greeting">Hello, World!</h1>;

As you can see, the JSX code is more concise and easier to read. It looks similar to the HTML code you might already be familiar with, making it more intuitive for developers.

Using JSX in React

Now that we have an idea of what JSX is and why it's useful, let's see how to use it in a React application. To create a React element using JSX, you simply write the JSX code as shown below:

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

This code creates a new React element that represents an <h1> tag with the content "Hello, World!". You can then render this element using React's ReactDOM.render() method:

import React from 'react';
import ReactDOM from 'react-dom';

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

ReactDOM.render(element, document.getElementById('root'));

In this example, we import the React and ReactDOM libraries, create a new React element using JSX, and render it to the DOM element with the ID root.

Components and JSX

One of the main features of React is its ability to create reusable components. Components are the building blocks of a React application and can be thought of as custom HTML elements with their own behavior and properties.

To create a React component, you can define a JavaScript function that returns a JSX element:

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

This function, Greeting, is now a React component that can be used like any other HTML element:

const element = <Greeting />;

You can also pass data to components using props. Props are like HTML attributes that you can pass to a component to customize its behavior or appearance. Here's an example:

function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

const element = <Greeting name="Alice" />;

In this example, we pass a name prop to the Greeting component. The component then uses this prop to display a custom message.

JSX Expressions

One of the powerful features of JSX is the ability to embed JavaScript expressions within the JSX code. You can do this by wrapping the expression in curly braces ({}). Here's an example:

const name = "Alice";
const element = <h1>Hello, {name}!</h1>;

In this example, we use a JavaScript expression to display the value of the name variable within the JSX code. This is similar to using string interpolation in other programming languages.

You can use any valid JavaScript expression within the curly braces, including variables, functions, and even complex expressions:

function formatName(user) {
  return `${user.firstName} ${user.lastName}`;
}

const user = {
  firstName: "Alice",
  lastName: "Smith",
};

const element = <h1>Hello, {formatName(user)}!</h1>;

In this example, we use a function, formatName, to format the user's full name within the JSX code.

JSX Attributes

You can also set attributes on JSX elements, just like you would with HTML elements. To set an attribute, simply include it within the opening tag of the JSX element:

const element = <img src="logo.png" alt="Logo" />;

In this example, we set the src and alt attributes on an <img> element.

Note that some attribute names are different in JSX than they are in HTML. This is because JSX is more closely related to JavaScript than HTML. For example, the class attribute is called className in JSX, and the for attribute is called htmlFor. You can find a full list of supported attributes in the React documentation.

Conditional Rendering

You can use JavaScript expressions to conditionally render elements in JSX. This means you can decide whether to render an element or not based on some condition. Here's an example:

function Greeting(props) {
  if (props.isLoggedIn) {
    return <h1>Hello, {props.name}!</h1>;
  } else {
    return <h1>Please log in.</h1>;
  }
}

const element = <Greeting isLoggedIn={false} name="Alice" />;

In this example, we only render the personalized greeting if the isLoggedIn prop is true. Otherwise, we render a generic message asking the user to log in.

JSX Fragments

Sometimes you might want to return multiple elements from a component without having to wrap them in a parent element. This can be useful when working with lists or other situations where a wrapper element might cause problems with CSS or layout.

In these cases, you can use a JSX fragment to group the elements without adding an extra node to the DOM. A JSX fragment looks like an empty pair of angle brackets (<>...):

function ListItem(props) {
  return (
    <>
      <dt>{props.term}</dt>
      <dd>{props.definition}</dd>
    </>
  );
}

const element = (
  <dl>
    <ListItem term="React" definition="A JavaScript library for building user interfaces." />
    <ListItem term="JSX" definition="A syntax extension for JavaScript that allows you to write HTML-like code within your JavaScript code." />
  </dl>
);

In this example, we use a JSX fragment to return two elements, <dt> and <dd>, without having to wrap them in a parent element.

Conclusion

JSX is an important part of the React ecosystem and provides a more intuitive way to write JavaScript code that manipulates HTML elements. It makes it easier to read and maintain your code by allowing you to mix JavaScript and HTML together in a natural way.

In this article, we've learned what JSX is, why it's useful, and how to use it in a React application. We've also seen some examples of how to use JSX expressions, attributes, and fragments to create and manipulate React elements.

Now that you have a better understanding of JSX, you can start using it in your own React applications to create more maintainable and readable code.