Embedding JavaScript in JSX: Dynamic Markup
JSX's real power lies in blending HTML-like markup with JavaScript logic using curly braces {}. This technique allows you to embed variables, expressions, and function calls directly into your components, transforming static markup into dynamic, responsive interfaces. Understanding how to use curly braces as a gateway to JavaScript is fundamental to writing modern React code.
Key Takeaways
- Curly braces
{}let you write JavaScript expressions inside JSX markup - Use
{}for dynamic text content, attributes, and function calls - The
style={{...}}pattern is two JavaScript features layered: expression braces and object literals - Expressions (not statements) evaluate to values; you cannot write
ifstatements or loops directly inside braces - Keep expressions simple and readable by computing complex logic before the
returnstatement
The Core Concept: A Window to JavaScript
JSX is not a separate templating language—it is JavaScript with HTML-like syntax. The curly brace {} is the mechanism that lets you access JavaScript from within JSX markup.
Think of it this way:
- Outside the braces: You are in "JSX land," writing HTML-like markup.
- Inside the braces: You are in "JavaScript land," where you can write any valid JavaScript expression.
An expression is a piece of code that evaluates to a single value. Key distinction: you cannot write a full if statement or for loop inside the braces, but you can use expressions like 2 + 2, user.name, items.length, or formatDate(today).
How Do You Render Variables as Text in JSX?
The most common use case is displaying dynamic data. Instead of hardcoding text, embed a variable inside curly braces.
import React from 'react';
function UserGreeting() {
const userName = 'Hedy Lamarr';
return <h1>Welcome, {userName}!</h1>;
}
export default UserGreeting;
Step-by-Step Breakdown:
const userName = 'Hedy Lamarr';— Declare a standard JavaScript variable.<h1>Welcome, {userName}!</h1>— Inside the h1, use curly braces to embed the variable. React evaluates the expression, finds its value, and renders it to the DOM. The final output is<h1>Welcome, Hedy Lamarr!</h1>.
How Do You Set Dynamic Attributes in JSX?
You can use curly braces to set attributes dynamically—useful for image sources, links, or ARIA labels. When passing a string literal, use quotes; when passing a dynamic value, use curly braces.
import React from 'react';
function UserAvatar() {
const user = {
name: 'Gregorio Y. Zara',
imageUrl: 'https://i.imgur.com/7vQD0fPs.jpg'
};
return (
<img
className="avatar"
src={user.imageUrl}
alt={'Photo of ' + user.name}
/>
);
}
export default UserAvatar;
Walkthrough:
className="avatar"— Static string uses double quotes.src={user.imageUrl}— Dynamic attribute uses curly braces to reference the property.alt={'Photo of ' + user.name}— You can perform operations inside braces, such as concatenating a string with an object property.
What Does the Double-Curly Brace Syntax {{...}} Mean?
The style={{...}} syntax confuses many beginners, but it is simply two JavaScript features layered together: not special React syntax.
- The outer curly braces
{...}open a window to JavaScript. - The inner curly braces
{...}create a JavaScript object literal.
The style attribute in React does not accept a string of CSS (like HTML). Instead, it accepts a JavaScript object where keys are camelCased CSS properties.
import React from 'react';
function StyledCard() {
const cardStyles = {
backgroundColor: '#f0f0f0',
borderRadius: '8px',
padding: '16px',
boxShadow: '0 4px 8px rgba(0,0,0,0.1)'
};
return (
<div style={cardStyles}>
<h3 style={{ color: 'purple' }}>A Styled Card</h3>
<p>This card uses JavaScript objects for styling.</p>
</div>
);
}
export default StyledCard;
Code Breakdown:
const cardStyles = {...}— Define styles as a standard JavaScript object.<div style={cardStyles}>— Pass the object using a single pair of braces (it is a variable).<h3 style={{ color: 'purple' }}>— Inline style object: outer{}opens JavaScript; inner{ color: 'purple' }is the actual object.
How Do You Call Functions Inside JSX?
Because you can use any JavaScript expression, you can also call functions directly from within JSX. This is excellent for formatting data.
import React from 'react';
const today = new Date();
function formatDate(date) {
return new Intl.DateTimeFormat(
'en-US',
{
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
}
).format(date);
}
function DateDisplay() {
return (
<div>
<p>Today is: {formatDate(today)}</p>
</div>
);
}
export default DateDisplay;
Here, {formatDate(today)} is evaluated: the function is called with the today variable, and the returned string is rendered inside the paragraph.
Best Practices for Embedding JavaScript
- Keep expressions simple: While you can embed complex logic in JSX, it is cleaner to compute the data in variables before the
returnstatement. This keeps markup focused on structure. - Always use braces for dynamic values: A common mistake is omitting braces (e.g.,
src="myVariable"passes the literal string instead of the variable). - Objects require double braces: The
styleprop and other object-based attributes need the "double-curly" syntax when defined inline. - Prepare data before rendering: Complex calculations belong in functions or variables above
return, not nested inside JSX expressions.
Frequently Asked Questions
Can you write an if statement inside curly braces in JSX?
No. You can only write expressions inside curly braces—code that evaluates to a value. Statements like if, for, or while do not evaluate to a value. Instead, use a ternary operator: {condition ? trueValue : falseValue} or compute the value before the return.
What is the difference between style="color: red" and style={{ color: 'red' }}?
In HTML, style accepts a string of CSS. In React JSX, style accepts a JavaScript object with camelCased keys. The outer braces open JavaScript; the inner braces create the object literal. React then converts the object to inline CSS.
Can you access component props inside curly braces?
Yes. Props are JavaScript variables passed to your component function. You can access them directly inside curly braces: <h1>{props.title}</h1> or <h1>{title}</h1> if you destructure the props.
What happens if you forget the curly braces around a dynamic attribute?
React treats it as a literal string. For example, src="imageUrl" renders the string "imageUrl" as the src, not the value of the imageUrl variable. You must use src={imageUrl} to pass the variable.
Are there any performance concerns with calling functions inside JSX?
Yes. Functions called in JSX are re-executed on every render. For expensive operations, use the useMemo or useCallback hooks to memoize the result and avoid unnecessary recalculations.