In JSX, you can include JavaScript expressions by enclosing them within curly braces {}
. This allows you to dynamically insert values, perform calculations, or execute JavaScript logic within your JSX code.
Here are some examples of using expressions in JSX:
- Inserting a variable value:
import React from 'react';
function MyComponent() {
const name = 'John Doe';
return <h1>Hello, {name}!</h1>;
}
In this example, the value of the name
variable is dynamically inserted within the JSX code, resulting in a personalized greeting.
- Evaluating an expression:
import React from 'react';
function MyComponent() {
const a = 10;
const b = 5;
return <p>The sum of {a} and {b} is {a + b}.</p>;
}
Here, the expression {a + b}
is evaluated within the JSX code, and the result is displayed as part of the paragraph.
- Using conditional expressions:
import React from 'react';
function MyComponent() {
const isLoggedIn = true;
return (
<div>
{isLoggedIn ? <p>Welcome, User!</p> : <p>Please log in.</p>}
</div>
);
}
In this example, the ternary operator isLoggedIn ? <p>Welcome, User!</p> : <p>Please log in.</p>
is used to conditionally render different elements based on the value of isLoggedIn
.
By incorporating JavaScript expressions within curly braces {}
, you can dynamically generate content, calculate values, and conditionally render components in JSX, making your React components more versatile and interactive.