JSX: Expressions
JSX isn't just for static markup. You can embed JavaScript expressions directly within your JSX code, making your components dynamic. This is done using curly braces {}.
What are Expressions?
An expression in JavaScript is anything that evaluates to a value. This includes:
- Variables
- Function calls
- Arithmetic operations
- String concatenation
- Conditional (ternary) operators
- And more!
How to Use Expressions in JSX
To embed an expression, simply wrap it in curly braces {} within your JSX. React will evaluate the expression and render its result.
Examples
Rendering a Variable:
function MyComponent() { const name = "Alice"; return ( <h1>Hello, {name}!</h1> ); }This will render:
<h1>Hello, Alice!</h1>Calling a Function:
function MyComponent() { function formatDate(date) { return new Intl.DateTimeFormat('en-US').format(date); } const currentDate = new Date(); return ( <p>Today is {formatDate(currentDate)}</p> ); }This will render a paragraph with the current date formatted.
Performing Arithmetic:
function MyComponent() { const a = 10; const b = 5; return ( <p>The sum of {a} and {b} is {a + b}</p> ); }This will render:
<p>The sum of 10 and 5 is 15</p>Using a Conditional (Ternary) Operator:
function MyComponent({ isLoggedIn }) { return ( <div> {isLoggedIn ? ( <p>Welcome back!</p> ) : ( <p>Please log in.</p> )} </div> ); }This component renders different content based on the
isLoggedInprop.Rendering a JavaScript Object as a String:
function MyComponent() { const user = { name: "Bob", age: 30 }; return ( <p>User: {JSON.stringify(user)}</p> ); }This will render:
<p>User: {"name":"Bob","age":30}</p>(Note the use ofJSON.stringifyto convert the object to a string).Rendering an Array:
function MyComponent() { const items = ['Apple', 'Banana', 'Orange']; return ( <ul> {items.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> ); }This renders a list of items. Important: When rendering lists, always provide a unique
keyprop to each element.
Important Considerations:
- JavaScript Statements vs. Expressions: You can only use expressions inside JSX. Statements (like
iforforloops) are not allowed directly. You can use expressions within statements, but not the statements themselves. For example, you can use a ternary operator (an expression) to conditionally render content, but you can't write a fullif/elseblock directly in JSX. - Readability: While powerful, excessive use of expressions can make your JSX harder to read. Consider extracting complex logic into separate functions to improve clarity.
- Security: Be mindful of security when rendering user-provided data. Always sanitize or escape data to prevent cross-site scripting (XSS) vulnerabilities.
By leveraging expressions within JSX, you can create dynamic and interactive React components that respond to data and user interactions.