Introduction
JSX stands for JavaScript XML. It is a special way of writing code in JavaScript that looks like HTML but works inside JavaScript files. It helps developers write UI (user interface) elements in a more visual and readable format. In React, JSX is used to describe what the UI should look like.
Example
const element = <h1>Hello, World!</h1>;
Here, <h1>Hello, World!</h1> looks like HTML, but it’s JSX. React will turn this into plain JavaScript that the browser can understand.
Why Use JSX in React?
- Readable Code: Instead of writing complex JavaScript functions for UI, JSX lets you write HTML-like code, making it easier to understand.
- Integration with JavaScript: You can mix HTML-like syntax with JavaScript logic, for example, inserting variables or results of calculations directly into the UI.
- Component Creation: Writing components becomes easier since you can describe the UI directly inside your JavaScript code.
- Tooling Support: Code editors can highlight errors, suggest code, and format JSX for better productivity.
Example
const name = "John";
const element = <h1>Hello, {name}!</h1>;
Here, {name} is a JavaScript variable whose value is displayed inside the <h1> tag.
How JSX Works Behind the Scenes?
Browsers cannot directly understand JSX. Before running in the browser, JSX is converted into plain JavaScript using a compiler like Babel.
For example
const element = <h1>Hello, World!</h1>;
Babel changes this into.
const element = React.createElement('h1', null, 'Hello, World!');
React.createElement() creates a React element (a JavaScript object) that React can use to display things on the screen.
Embedding JavaScript in JSX
With JSX, you can insert JavaScript expressions directly inside curly braces {}. This allows you to show dynamic content.
Example
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
<Greeting name="Alice" />
Here, {props.name} is replaced with the value “Alice” when the component is rendered.
JSX Rules to Remember
- Return a single parent element: Wrap multiple elements inside one parent, like a <div> or a React fragment.
return (
<div>
<h1>Hello</h1>
<p>World</p>
</div>
);
- Close all tags: Even tags that don’t have content, like <img />, must be closed.
- Use className instead of class: In JSX, class is a reserved JavaScript word.
- Use curly braces for JavaScript: Only JavaScript expressions should go inside {}.
Summary
JSX is a React feature that lets you write HTML-like code inside JavaScript, making it easier to design and manage user interfaces. While browsers don’t understand JSX directly, tools like Babel convert it into React.createElement() calls, which React uses to render UI elements. This combination of HTML-like syntax and JavaScript logic makes JSX a powerful and convenient way to build dynamic applications.