What is JSX?
JSX stands for JavaScript XML, is a syntax extension for JavaScript used in React to describe what the UI should look like. It allows us to write HTML elements directly within JavaScript code.
HTML-like Syntax: JSX looks similar to HTML, making it intuitive for developers who are already familiar with web development.
Embedded in JavaScript: JSX allows you to write HTML-like code within JavaScript files, making the code more cohesive and easier to maintain.
Transpiled by Babel: Browsers do not understand JSX directly. It is transpiled by tools like Babel into standard JavaScript code that browsers can execute.
const element = <h1>Hello, world!</h1>;
In this example, <h1>Hello, world!</h1>
is JSX. This line of code creates a React element that represents an HTML h1
element with the text “Hello, world!”.
How Its Works
Embedding Expressions:
We can embed JavaScript expressions inside JSX using curly braces {}
.
const name = 'Ram';
const element = <h1>Hello, {name}!</h1>;
In this example, {name}
is replaced with the value of the name
variable, resulting in <h1>Hello,Ram!</h1>
.
Attributes and Props:
JSX allows you to set attributes and pass props to components using a syntax similar to HTML
const element = <img src="logo.png" alt="Logo" />;
Children (Nested Elements):
JSX can have children elements, allowing you to nest elements within each other.
For nested elements we can use html tag (e.g., <div>
, <span>
), Arrays and React Fragment
const element = ( <div> <h1>Hello, world!</h1> <p>Welcome to React.</p> </div> );
HTML Elements
The most straightforward way to group elements is by using standard HTML tags.
These elements create new nodes in the DOM.
When you need a container for styling or layout purposes. Applying CSS styles or using flexbox/grid layouts.
React Fragments
React Fragments let you group multiple children without adding extra nodes to the DOM.
Available in two syntaxes: the shorthand <>...</>
and the full syntax <React.Fragment>...</React.Fragment>
.
function App() {
return (
<>
<h1>Hello, world!</h1>
<p>Welcome to React.</p>
</>
);
}
function App() {
return (
<React.Fragment>
<h1>Hello, world!</h1>
<p>Welcome to React.</p>
</React.Fragment>
);
}
Arrays
You can return an array of elements from a component.
Each element in the array should have a unique key.
function App() {
return [
<h1 key="1">Hello, world!</h1>,
<p key="2">Welcome to React.</p>
];
}
Useful when you need to dynamically generate elements based on data.
JavaScript Expressions:
You can use any valid JavaScript expression inside JSX, such as mathematical calculations or function calls.
const element = <p>{10 + 5}</p>;
This results in <p>15</p>
because 10 + 5
is evaluated to 15
.
Conditional Rendering:
Conditional logic can be implemented inside JSX using ternary operators or logical ‘&&'
.
const isLoggedIn = true;
const element = <div>{isLoggedIn ? <p>Welcome back!</p> : <p>Please sign in.</p>}</div>;
const element = <div>{isLoggedIn && <p>Welcome back!</p>}</div>;
This renders <p>Welcome back!</p>
if isLoggedIn
is true
, otherwise <p>Please sign in.</p>
and for logical operators if isLoggedIn
is true
then renders <p>Welcome back!</p>
else empty <div></div>
Benefits of JSX
- Improved Readability: The HTML-like syntax makes the UI structure more readable and understandable at a glance.
- Enhanced Developer Experience: With JSX, developers can write components in a more declarative style, which is easier to reason about.
- Better Integration: Since JSX is embedded in JavaScript, it allows for seamless integration of logic and UI, avoiding the separation seen in traditional templating systems.
How JSX is Transpiled
JSX is not understood by browsers directly. Therefore, it needs to be transpiled into regular JavaScript before it can be executed. This is usually done using a tool like Babel.
JSX -
const element = <h1>Hello, world!</h1>;
is transpiled to:
const element = React.createElement('h1', null, 'Hello, world!');
Type: The first argument is the type of the element, in this case, 'h1'
.
Props: The second argument is an object containing the element’s props. Here, null
indicates no props.
Children: The third argument (and subsequent ones) represents the children of the element. In this example, it’s the text node 'Hello, world!'
.
Transpilation: The JSX code is then transformed by Babel into React.createElement
calls. This transformation converts the JSX syntax into a format that browsers can understand and execute.
Steps of Transpilation:
- Parse JSX: Babel parses the JSX code and constructs an Abstract Syntax Tree (AST) to understand the structure of the code.
- Transform JSX to JavaScript: Babel transforms the AST nodes representing JSX elements into JavaScript code using React.createElement.
- Output JavaScript: The transformed JavaScript code is then outputted, ready to be executed by the browser.