What is JSX in React?
JSX (JavaScript XML) is a syntax extension for JavaScript, commonly used with React to describe what the UI should look like. It allows developers to write HTML-like code directly within JavaScript, making the structure of components more intuitive and readable.
Instead of using React.createElement()
to create elements manually, JSX lets you write code that closely resembles the final HTML output, which React then compiles into JavaScript objects behind the scenes.
Example of JSX:
const element = <h1>Hello, world!</h1>;
Without JSX (using React.createElement
):
const element = React.createElement('h1', null, 'Hello, world!');
Key Points about JSX:
- JSX must have only one parent element (use fragments
<>
or a wrapper<div>
if needed). - You can embed JavaScript expressions inside JSX using curly braces
{}
. - JSX attributes use camelCase naming conventions (e.g.,
className
instead ofclass
,htmlFor
instead offor
). - Under the hood, JSX is transformed into regular JavaScript by tools like Babel.
Why use JSX?
- Improved readability: Code looks similar to HTML.
- Power of JavaScript: Dynamic content can be easily integrated.
- Better tooling: JSX has excellent support in IDEs (autocomplete, error checking).