Hello! Welcome to your fourth lesson in the "React Fundamentals and JSX" module.
In our last lesson, we explored the "what" and "how" of JSX. You learned that it's a syntax extension for JavaScript, that it gets compiled into standard JavaScript function calls, and the basic rules for writing it, like returning a single root element and using className. So far, we've only dealt with static markup.
Today, we'll bring our components to life. This lesson fulfills the learning outcome: Embed JavaScript expressions in JSX using curly braces. We will explore how the {} syntax acts as a "window" into JavaScript, allowing us to render dynamic data, call functions, and use JS logic directly within our UI descriptions. This is a fundamental concept that transforms JSX from a simple templating tool into a powerful, expressive way to build user interfaces.
Using Curly Braces: A Window into the JavaScript World
JSX would be very limited if we could only write static markup. The real power of React comes from its ability to seamlessly blend markup with JavaScript logic. The mechanism for this is the curly brace {}.
Whenever you want to switch from "JSX mode" to "JavaScript mode," you use curly braces. Inside them, you can put variables, function calls, or any other JavaScript code that results in a value.
To get a foundational understanding of this concept, please read the first few sections of the official React documentation on this topic.
JavaScript in JSX with Curly Braces
The official React documentation, 'JavaScript in JSX with Curly Braces', clearly explains how to use curly braces to inject dynamic values from your JavaScript code into your JSX markup.
Read from the beginning down to the section titled 'Using “double curlies”: CSS and other objects in JSX'. Focus on the core idea: replacing hard-coded string attributes or text with JavaScript variables wrapped in curly braces.
Let's put this into practice. Open your src/App.tsx file and replace its contents with the following code:
function App() {
const userName: string = 'Shinji Ikari';
const episodeNumber: number = 4;
const imageUrl: string = 'https://i.imgur.com/7vQD0fPs.jpg'; // A generic placeholder
const altText: string = 'A profile picture';
return (
<>
<h1>Welcome, {userName}</h1>
<p>You are watching episode {episodeNumber}.</p>
<img
className="avatar"
src={imageUrl}
alt={altText}
/>
<p>The current year is {new Date().getFullYear()}.</p>
</>
);
}
export default App;
Here, we are:
- Rendering the
userNamestring inside an<h1>tag. - Displaying the
episodeNumbernumber within a paragraph. - Using the
imageUrlandaltTextvariables to dynamically set thesrcandaltattributes of the<img>tag. - Calling the
new Date().getFullYear()function directly in JSX. The function executes, and its return value (the current year) is rendered.
This demonstrates the two places you can use curly braces:
- As text content directly inside a JSX tag (e.g.,
<h1>{userName}</h1>). - As attribute values, immediately following the
=sign (e.g.,src={imageUrl}).
What Can You Put Inside Curly Braces? Expressions vs. Statements
This leads to a critical question: what kind of JavaScript can go inside {}? The answer is precise: you can only put JavaScript expressions inside curly braces.
Since you have a strong background in computer science and JavaScript, this distinction will be key to mastering React. Let's formalize it:
-
An Expression is a piece of code that evaluates to (or "produces") a single value. Examples include:
1 + 1(evaluates to2)user.name(evaluates to the value of thenameproperty)myFunction()(evaluates to the function's return value)isLoggedIn ? 'Log Out' : 'Log In'(evaluates to one of the two strings)
-
A Statement is a complete instruction that performs an action. Statements do not produce a value. Examples include:
let x = 5;(a variable declaration)if (condition) { ... } else { ... }(an if-else block)for (let i = 0; i < 5; i++) { ... }(a for loop)
Why this matters for React: JSX is transformed into React.createElement(type, props, ...children) function calls. The values inside the curly braces become arguments to these functions. Since function arguments must be values (i.e., the results of expressions), you cannot pass a whole if statement or a for loop as an argument.
For a deeper dive into this fundamental JavaScript concept and its direct impact on how you write React code, the following article is an excellent resource.
Josh W. Comeau's article 'Statements Vs. Expressions' provides a clear and detailed explanation of this distinction, complete with a section on its practical implications in React.
Read the article up to and including the section 'Practical implications in React'. Pay special attention to the handy trick of using console.log() to test if something is an expression and how this logic applies directly to JSX's curly braces.
Test your understanding!
Based on the distinction between expressions and statements, which of the following lines would cause an error if placed inside an <h1> tag in JSX?
{ 2 * 21 }{ const x = 10; }{ 'Evangelion ' + 'Unit-01' }{ if (true) { 'Hello' } }{ new Date().toString() }
Show answer
Lines 2 and 4 would cause an error.
const x = 10;is a variable declaration statement. It doesn't produce a value to be displayed.if (true) { 'Hello' }is anifstatement. It's an instruction, not an expression that resolves to a value.
The other lines are all valid expressions that produce a value (a number, a string), so they are valid inside JSX curly braces.
The "Double Curly" Syntax for Styles
You will often see this syntax for applying inline styles in React, which can be confusing at first: style={{ color: 'red' }}.
This is not special syntax. It's a direct application of the rules we've just learned. Let's break it down:
- The outer curly braces
{...}open the "window to JavaScript" in JSX. React is now expecting an expression. - The inner curly braces
{{...}}are the expression itself: a standard JavaScript object literal.
In React, the style attribute does not accept a string of CSS like in HTML. Instead, it accepts a JavaScript object where the keys are camelCased versions of CSS properties.
// This is more readable when you define the object first
const headingStyle = {
backgroundColor: 'black', // background-color in CSS
color: 'pink', // color in CSS
padding: '16px' // padding in CSS
};
return <h1 style={headingStyle}>Styled Heading</h1>;
The "double curly" syntax is just an inline version of the above:
return <h1 style={{ backgroundColor: 'black', color: 'pink' }}>Styled Heading</h1>;
The React docs provide a great summary of this and other uses of objects in JSX.
JavaScript in JSX with Curly Braces
Let's return to the React documentation to see how objects are used in JSX, focusing on the 'double curlies' for styling.
Read the sections 'Using “double curlies”: CSS and other objects in JSX', 'More fun with JavaScript objects and curly braces', and the 'Recap'. This will solidify your understanding of the style prop and how to organize data in objects for rendering.
Now let's watch a short video that ties these concepts together, explaining the boundary between what can and cannot go inside JSX curly braces.
What is JSX in React? Fully Explained
This video from Code Ryan provides a practical walkthrough of embedding JavaScript in JSX and clearly distinguishes between allowed expressions (like variables and ternaries) and disallowed statements (like if statements and for loops).
Watch from 13:01 to 20:26. This segment will reinforce everything we've discussed: embedding variables, the limitations of expressions vs. statements, and the common patterns used for conditional logic (which is a preview for our next lesson!).
Conclusion
Today, you've unlocked the dynamic capabilities of JSX. By understanding how to use curly braces, you can now connect your component's logic and data directly to the markup it renders.
Key Takeaways:
- The Gateway to JS: Curly braces
{}are used in JSX to embed JavaScript. - Expressions Only: Only JavaScript expressions—code that produces a value—can be placed inside the curly braces. Statements like
if/elseorforloops are not allowed. - Dynamic Content and Attributes: You can use expressions to render text content and to provide values for attributes like
srcorstyle. - The "Double Curly" Demystified: The
style={{...}}syntax is simply a JavaScript object literal (an expression) passed inside the JSX curly braces.
We briefly touched upon the idea of using expressions like the ternary operator for conditional logic. In our next lesson, we will build directly on that idea as we tackle our next outcome: "Apply conditional rendering using JavaScript operators and ternary expressions in JSX". You'll learn the standard React patterns for showing, hiding, or changing UI based on your application's state.