Skip to main content

JSX Expressions (Live Playground)

JavaScript expressions are a powerful feature of JSX that allows you to create dynamic content and conditional rendering in your React components. In this tutorial, we'll explore how to use JavaScript expressions within JSX, along with sample code and simple explanations.

Embedding JavaScript Expressions

You can embed JavaScript expressions within your JSX code by wrapping them in curly braces ({}). Here's an example of using a JavaScript expression in JSX:

JavaScript
const name = 'John Doe';
const element = <h1>Hello, {name}!</h1>;

In this example, we used a JavaScript expression to display the value of the name variable within the <h1> element.

Live Playground, Try it Yourself

Arithmetic Expressions

You can use arithmetic expressions within your JSX code to perform calculations and display the results. Here's an example of using an arithmetic expression in JSX:

JavaScript
const a = 10;
const b = 20;
const element = <p>The sum of a and b is {a + b}.</p>;

In this example, we used an arithmetic expression to calculate the sum of a and b and display the result within the <p> element.

Live Playground, Try it Yourself

Ternary Operator for Conditional Rendering

You can use the ternary operator (condition ? expr1 : expr2) within your JSX code to conditionally render content. Here's an example of using the ternary operator in JSX:

JavaScript
const isLoggedIn = true;
const element = <h1>{isLoggedIn ? 'Welcome, user!' : 'Please log in.'}</h1>;

In this example, we used the ternary operator to conditionally display "Welcome, user!" if isLoggedIn is true, and "Please log in." if isLoggedIn is false.

Live Playground, Try it Yourself

Rendering Arrays and Lists

You can use JavaScript expressions within your JSX code to render arrays and lists. Here's an example of rendering a list of items using the Array.prototype.map() method:

JavaScript
const items = ['Apple', 'Banana', 'Cherry'];
const element = (
<ul>
{items.map(item => (
<li key={item}>{item}</li>
))}
</ul>
);

In this example, we used the map() method to create a new array of <li> elements, each containing an item from the items array. The key attribute is used to uniquely identify each list item.

Live Playground, Try it Yourself

Conclusion

JavaScript expressions in JSX are a powerful tool for creating dynamic content and conditional rendering in your React components. By understanding how to use expressions, arithmetic operations, ternary operators, and rendering arrays, you'll be better equipped to build interactive and dynamic user interfaces. With a strong foundation in JSX expressions, you'll be well on your way to becoming an effective React developer.