JSX in Arrays and Objects
What you'll learn: How to organize multiple JSX elements in arrays and objects for dynamic, flexible component composition.
The Core Idea
Since JSX elements are just JavaScript objects (as you learned previously), you can store them in any JavaScript data structure. This means you can create arrays of JSX elements or organize them in objects with meaningful keys. This unlocks powerful patterns for dynamically selecting which content to render or managing collections of related UI pieces.
Arrays of JSX Elements
The most common pattern is storing multiple elements in an array:
const buttons = [
<button key="save">Save</button>,
<button key="cancel">Cancel</button>,
<button key="delete">Delete</button>
];
return <div>{buttons}</div>;
React will render all elements in the array. Remember that each element needs a key prop when rendered from arrays.
Objects with JSX Values
You can also organize JSX by name in an object:
const icons = {
success: <CheckIcon />,
error: <XIcon />,
warning: <AlertIcon />
};
// Later, dynamically select which to render
return <div>{icons[status]}</div>;
This pattern is incredibly useful for mapping states or types to their corresponding UI representations.
Why This Matters
These structures enable dynamic composition: you can build collections of UI elements, filter them, reorder them, or select from them based on runtime conditions—all using standard JavaScript array and object methods.
Key Takeaway: Storing JSX in arrays and objects transforms your UI into data you can manipulate with JavaScript, enabling dynamic selection, filtering, and composition patterns that would be cumbersome with conditional rendering alone.