Projects

Introduction to JSX (JavaScript XML)

Now that you’ve set up your React project and understand its structure, the next step is learning how to build the user interface of your app. In React, we use something called JSX to create the UI.

What is JSX?

JSX stands for JavaScript XML. It’s a syntax that allows us to write HTML-like code inside JavaScript. JSX is very useful because it makes it easier to visualize the structure of your user interface right inside your JavaScript code.

If you’ve written HTML before, JSX will look familiar, but there are some differences you need to keep in mind.

Why Use JSX?

JSX is used in React to describe what the UI should look like. Instead of separating HTML and JavaScript into two different files, JSX allows you to write them together in a more natural way. This keeps your code cleaner and easier to manage, especially as your app grows.

Behind the scenes, JSX is converted to JavaScript. So, when the browser reads your code, it’s actually dealing with JavaScript, not raw HTML. But don’t worry—React handles this conversion for you, so you don’t have to think about it.

How JSX Works

JSX looks like HTML but is actually JavaScript. It allows you to create components (which you’ll learn more about soon) and dynamically update your UI based on user interaction or data changes.

For example, here’s a simple JSX element:


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

This looks like an HTML <h1> element, but it's actually JSX, which React will convert into JavaScript code.

Where Does JSX Fit in the Project?

In the project structure we explored earlier, you’ll typically see JSX used inside the App.js file and any new components you create. Every time you want to define what your UI looks like, you’ll be using JSX.

Remember the <div id="root"></div> inside the index.html file in the public/ folder? React uses JSX to "inject" your components into that div . This is how everything you build using JSX shows up in the browser.

JSX is More Powerful Than HTML

Unlike regular HTML, JSX allows you to embed JavaScript code inside it. This means you can dynamically control your UI based on data, conditions, or user actions. You can also reuse components, making your code more efficient.

Let’s see an example where we use JSX to display dynamic data:


const name = 'Medi';
const element = <h1>Hello, {name}!</h1>;

In this example, name is JavaScript code that will be replaced by the value of the variable name . When this runs, the browser will display Hello, Medi! .

Wrapping Up JSX

JSX is an important concept to understand because it forms the foundation of how you’ll build React apps. You use it to define your UI and control how elements are displayed on the screen.

Now that you have a basic understanding of JSX, let’s dive deeper into its syntax and best practices, so you can start writing clean and efficient JSX code.