What is JSX and how does it work?
TL;DR
JSX stands for JavaScript XML. It is a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript. JSX makes it easier to create React components by allowing you to write what looks like HTML directly in your JavaScript code. Under the hood, JSX is transformed into JavaScript function calls, typically using a tool like Babel. For example, <div>Hello, world!</div>
in JSX is transformed into React.createElement('div', null, 'Hello, world!')
.
What is JSX and how does it work?
What is JSX?
JSX stands for JavaScript XML. It is a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript. JSX is primarily used with React to describe what the UI should look like.
How does JSX work?
JSX is not valid JavaScript by itself. It needs to be transformed into regular JavaScript before it can be executed by the browser. This transformation is usually done by a tool like Babel.
JSX syntax
JSX allows you to write HTML-like tags directly in your JavaScript code. For example:
Transformation process
When you write JSX, it is transformed into JavaScript function calls. For example, the JSX code:
is transformed into:
Embedding expressions
You can embed JavaScript expressions inside JSX using curly braces {}
. For example:
Attributes in JSX
You can use quotes to specify string literals as attributes and curly braces to embed JavaScript expressions. For example:
JSX is an expression
After compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects. This means you can use JSX inside if statements, for loops, and assign it to variables.
JSX prevents injection attacks
By default, React DOM escapes any values embedded in JSX before rendering them. This ensures that you can never inject anything that’s not explicitly written in your application.