Course contentsShow
← React
Lesson 1139 of 2,39629. Composition: SlotsFree lesson

Storing JSX in Variables

Learn to assign JSX elements to variables for reuse, conditional rendering, or passing as props instead of rendering inline.

Storing JSX in Variables

You'll learn: How to assign JSX elements to variables for cleaner, more flexible component code.

The Core Idea

JSX elements aren't magic—they're just JavaScript objects that React knows how to render. This means you can store them in variables just like any other value. Instead of always writing JSX inline, you can assign it to a const or let, then use that variable wherever you need the content.

Think of it like writing a sentence on a sticky note. You can stick that note anywhere you need it, pass it to someone else, or decide whether to display it based on some condition. The sentence doesn't change, but where and when you use it becomes flexible.

Why Store JSX in Variables?

1. Reuse the same element multiple times:

const icon = <CheckIcon className="text-green-500" />;
return <div>{icon} Success {icon}</div>;

2. Conditional rendering without repetition:

const errorMessage = <p className="error">Invalid input</p>;
return isError ? errorMessage : null;

3. Pass JSX as props cleanly:

const header = <h1>Welcome</h1>;
return <Card headerSlot={header} />;

4. Build complex JSX step-by-step:

const title = <h2>Dashboard</h2>;
const subtitle = <p>Overview of your data</p>;
const header = <header>{title}{subtitle}</header>;

Variables make your render logic easier to read and maintain, especially when dealing with multiple slot props or conditional content sections.

Key Takeaway: JSX elements are objects you can store in variables—use them for reuse, cleaner conditional logic, or passing content to slot props instead of rendering everything inline.