What is JSX in React?
JSX stands for JavaScript XML. It's a syntax extension for JavaScript that allows you to write HTML-like code in JavaScript files. In React, JSX is used to build interfaces within components.
Although browsers can't directly understand JSX, it gets compiled into regular JavaScript code through Babel.
How JSX Works
// JSX example
const element = <h1>Hello, world</h1>;
// This JSX code compiles to this JavaScript
const element = React.createElement("h1", null, "Hello, world");
This means JSX is essentially syntactic sugar for React.createElement calls.
Using JavaScript Inside JSX
In JSX, we can use any JavaScript expression within `{}` curly braces.
const name = "Ani";
const greeting = <h1>Hello, {name}!</h1>;
This allows using variables, functions, conditions, and more.
Basic JSX Rules
- Only one root element in component returns
- HTML attributes must be camelCase (`class` → `className`)
- JavaScript expressions go inside `{}`
- All elements must be closed (`<img />`, `<br />`)
Complex JSX Structure
function Welcome(props) {
return (
<div className="container">
<h1>Hello, {props.name}!</h1>
<p>This is React's JSX.</p>
</div>
);
}
This is a component that uses JSX to build internal HTML and display data.
Advantages of JSX
- Simple syntax, readable code
- Combination of JavaScript and HTML in one place
- Great developer experience
In the next article, we'll talk about React components - functional vs class components, and how they work.
re