React JSX Basics

ReactBeginner
Practice Now

Introduction

Welcome to the world of React! In this lab, you'll dive into JSX, a fundamental part of building user interfaces with React. JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code directly within your JavaScript files. This makes your UI code more readable, expressive, and easier to maintain.

Throughout this lab, you will learn the core rules of JSX, including:

  • Writing HTML-like elements.
  • Embedding dynamic JavaScript expressions.
  • Applying CSS classes.
  • Using self-closing tags.
  • Grouping multiple elements with Fragments.

A basic React project has been set up for you in the ~/project/my-app directory. Let's get started!

Write JSX element like h1 in component return

In this step, you will write a basic JSX element and see it render in the browser. JSX allows you to write markup that looks very similar to HTML directly inside your React components.

First, let's get the development environment running. All your work will be inside the ~/project/my-app directory.

Navigate to the project directory in the terminal, install the necessary dependencies, and start the development server.

cd ~/project/my-app
npm install

After the installation is complete, run the following command to start the development server:

npm run dev -- --host 0.0.0.0 --port 8080

You will see output indicating that the server is running. Now, click on the Web 8080 tab at the top of the screen to see your live application. It should display "Hello, React!".

Next, open the src/App.jsx file from the file explorer on the left. This file contains a simple React component named App.

Let's modify the h1 element. Change the text inside the <h1> tag to "Welcome to JSX".

Replace the content of src/App.jsx with the following code:

import "./App.css";

function App() {
  return <h1>Welcome to JSX</h1>;
}

export default App;

Save the file (Ctrl+S or Cmd+S). The application in the Web 8080 tab will automatically update to show the new text.

Embed JavaScript expression in curly braces

In this step, you will learn how to embed JavaScript expressions directly into your JSX using curly braces {}. This is a powerful feature that allows you to render dynamic content.

You can place any valid JavaScript expression inside the curly braces. This could be a variable, a function call, or an arithmetic operation.

Let's modify the App component to display a dynamic title. Open the src/App.jsx file again.

Inside the App function, before the return statement, declare a JavaScript constant called title and assign it a string value. Then, use this constant inside the <h1> element.

Update your src/App.jsx file with the following code:

import "./App.css";

function App() {
  const title = "React JSX Basics";

  return <h1>{title}</h1>;
}

export default App;

Save the file. Now, check the Web 8080 tab. You will see that the heading has been updated to "React JSX Basics". React evaluates the expression {title} and renders its value as the content of the <h1> tag.

Add className attribute for CSS class

In this step, you'll learn how to add CSS classes to your JSX elements for styling.

In regular HTML, you use the class attribute to assign a CSS class. However, class is a reserved keyword in JavaScript. To avoid conflicts, JSX uses className instead.

First, let's add a style rule. Open the src/App.css file and add the following CSS code to define a style for our title:

.title-style {
  color: #61dafb;
  text-align: center;
}

Save the src/App.css file.

Now, let's apply this class to our <h1> element. Open src/App.jsx and add the className attribute to the h1 tag.

Update your src/App.jsx file to look like this:

import "./App.css";

function App() {
  const title = "React JSX Basics";

  return <h1 className="title-style">{title}</h1>;
}

export default App;

Save the file and switch to the Web 8080 tab. You should now see the title text centered and colored light blue, according to the styles you defined in App.css.

Use self-closing tag for img element

In this step, you will learn how to use self-closing tags in JSX. In HTML, some elements like <img>, <br>, and <input> are "void" or "empty" elements, meaning they don't have a closing tag.

In JSX, you must explicitly close every tag. For elements that don't have children, you use a self-closing syntax by adding a forward slash / before the closing angle bracket, like <img />.

A React component can only return a single root element. To render multiple elements, you must wrap them in a container, such as a <div>.

Let's add an image below our title. We'll wrap both the <h1> and the new <img> tag inside a <div>.

Update your src/App.jsx file with the following code:

import "./App.css";

function App() {
  const title = "React JSX Basics";
  const imageUrl = "https://labex.io/_ipx/s_98x30/labex-logo-light.svg";

  return (
    <div>
      <h1 className="title-style">{title}</h1>
      <img src={imageUrl} alt="LabEx Logo" width="200" />
    </div>
  );
}

export default App;

In this code, we've added an <img> tag. Notice it is self-closing (/>). We also used curly braces to dynamically set the src attribute from the imageUrl variable.

Save the file and look at the Web 8080 tab. You will see the LabEx logo displayed below the title.

Render multiple elements in fragment <> </>

In this step, you will learn a better way to group multiple elements without adding an extra node to the DOM: React Fragments.

In the previous step, we used a <div> to wrap our <h1> and <img> elements because a component must return a single root element. However, sometimes this extra <div> is unnecessary and can interfere with your CSS layout (e.g., with Flexbox or Grid).

React provides a solution called Fragments. A Fragment lets you group a list of children without adding extra nodes to the DOM. You can use the shorthand syntax <> ... </>.

Let's refactor our App component to use a Fragment instead of a <div>.

Open src/App.jsx and replace the opening <div> and closing </div> with <> and </> respectively.

Your final src/App.jsx code should look like this:

import "./App.css";

function App() {
  const title = "React JSX Basics";
  const imageUrl = "https://labex.io/_ipx/s_98x30/labex-logo-light.svg";

  return (
    <>
      <h1 className="title-style">{title}</h1>
      <img src={imageUrl} alt="LabEx Logo" width="200" />
    </>
  );
}

export default App;

Save the file. The visual output in the Web 8080 tab will look identical to the previous step. However, if you were to inspect the HTML in your browser's developer tools, you would see that the <h1> and <img> elements are now direct siblings, without a parent <div>. This creates a cleaner and more efficient DOM structure.

Summary

Congratulations on completing the React JSX Basics lab! You have learned the fundamental rules and syntax for writing UI in a React application.

In this lab, you practiced:

  • Writing HTML-like elements such as <h1> in your component's return statement.
  • Embedding dynamic JavaScript variables and expressions into your markup using curly braces {}.
  • Applying CSS classes using the className attribute.
  • Using self-closing tags for elements like <img> with the /> syntax.
  • Grouping multiple elements without adding extra DOM nodes by using React Fragments (<> </>).

These concepts are the building blocks for creating complex and dynamic user interfaces with React. Keep practicing to become more comfortable with the power and flexibility of JSX.