What is JSX in React?
JSX (JavaScript XML) is a syntax extension for JavaScript used in React to describe the user interface structure. JSX allows writing components that look like HTML but are actually JavaScript code.
Why JSX?
-
Convenience and readability. JSX allows describing interface elements in a familiar format similar to HTML, while having all the advantages of JavaScript.
-
Logic integration. JSX allows embedding JavaScript expressions directly into markup, simplifying the creation of dynamic and interactive interfaces.
-
Compilation to JavaScript. JSX is not standard JavaScript syntax, so it's compiled to regular JavaScript code using a transpiler like Babel.
JSX Usage Example
function Greeting() {
const name = "John";
return <h1>Hello, {name}!</h1>;
}
In this example, JSX is used to return an <h1> element that displays a greeting message. {name} is a JavaScript expression inserted inside JSX.
Important JSX Features
-
JSX elements must always be wrapped in one root element. For example, if multiple elements are returned, they need to be wrapped in a container like
<div>or use React.Fragment. -
JSX uses camelCase for naming attributes, such as className instead of class, and htmlFor instead of for.
JSX and components:
JSX makes it easy to create components with dynamic data and embedded logic. This simplifies creating interfaces in React.