JSX (JavaScript XML) is a syntax extension for JavaScript that looks similar to HTML or XML. It is used with React to describe what the UI should look like. Let’s break down the key concepts to understand JSX better.
What is JSX?
JSX allows you to write HTML-like code within JavaScript. It makes the code easier to understand and allows you to structure component rendering logic.
Example of JSX
const element = <h1>Hello, world!</h1>;
In this example, <h1>Hello, world!</h1>
is JSX. It looks like HTML but is JavaScript.
How JSX Works
Browsers can’t directly read JSX. Behind the scenes, a tool like Babel transpiles JSX into standard JavaScript. For instance, the above JSX code translates to:
const element = React.createElement('h1', null, 'Hello, world!');
Embedding Expressions in JSX
JSX is powerful because it allows embedding JavaScript expressions inside it. You can do this by wrapping the expressions in curly braces {}
.
Example of Embedding Expressions
const name = 'Junaid';
const element =<h1>Hello, world!</h1>;
Here, {name}
is a JavaScript expression embedded in JSX. When rendered, it will display “Hello, John!”.
You can also embed more complex expressions:
function formatName(user) {
return user.firstName + ' ' + user.lastName;
}
const user = {
firstName: 'Junaid',
lastName: 'Shaikh'
};
const element = <h1>Hello, {formatName(user)}!</h1>;
Embedding Expressions Example with Conditionals
You can use conditional expressions inside JSX:
const isLoggedIn = true;
const element = <h1>{isLoggedIn ? 'Welcome back!' : 'Please sign in.'}</h1>;