Remember when you started learning React and got stuck trying to show lists of data on your page? Those loops and if-statements were such a headache!
🧐 Picture this: you're writing clean React code that shows your data exactly how you want it, without breaking a sweat.
In this guide, we'll show you some simple tricks to handle your data like a pro. You'll learn how to turn messy code into something that's easy to read and works great!
Mapping Over Data
Alright, so let's suppose that the data for our Student Management App is held in an array, like this:
We want to create a <StudentCard>
element for each of the contacts in the data
array, passing in their name/job/email.
Unlike Vue and Angular, which provide special syntax for iteration, React uses pure JavaScript. There's no React-specific syntax for this task.
Take a moment to try solving this problem yourself! Don't worry if you're unsure—experimenting is the best way to develop your understanding. Play around 🎮 and see what happens.
I'll show you my solution below.
Solution code
import StudentCard from './StudentCard';
const data = [
{
id: 'louis-xyz456',
name: 'Louis Dupont',
email: 'louis.dupont@example.fr',
phone: '+33 1 23 45 67 89',
imgLink: '<https://avatar.iran.liara.run/public/31>'
},
{
id: 'anna-abc789',
name: 'Anna Müller',
email: 'anna.mueller@example.de',
phone: '+49 30 12345678',
imgLink: '<https://avatar.iran.liara.run/public/84>'
},
{
id: 'pierre-ghi012',
name: 'Pierre Martin',
email: 'pierre.martin@example.fr',
phone: '+33 4 56 78 90 12',
imgLink: '<https://avatar.iran.liara.run/public/26>'
}
];
function App() {
return (
<div>
{data.map((info) => (
<StudentCard
imgLink={info.imgLink}
name={info.name}
email={info.email}
phone={info.phone}
/>
))};
</div>
);
}
export default App;
Summary
→ Unlike other templating languages, React doesn't have special directives like v-for
or #each
for iteration.
→ React provides a simple way to handle arrays: pass the array directly, and React will render each item. For example, writing {['hello', 'world']}
renders "helloworld" in the DOM.
→ The solution is straightforward: create an array of React elements and pass it to React in the JSX.
→ While you could use a for loop to create this array of elements, the .map
method is the most elegant and commonly used approach.
→ Simply call data.map to render a <StudentCard/>
component for each item, then place that array in an expression slot inside the <ul/>
.
Note: You'll see a warning about missing keys in the developer console.
→ This is what makes React beautiful — instead of learning special syntax, you can leverage familiar JavaScript methods. Want to show only part of your array? Just use slice
!
Implementing solution
Implementing the solution code in the code playground
When iterating in React, it's not uncommon to wind up with structures like this:
<ul>
{items.map(item => (
<li>{item}</li>
))}
</ul>
On the second line, we use curly brackets to add some "vanilla JS" to our JSX. But then we're using JSX inside those curly brackets!
Keys
In the previous section, you may have noticed that we get a console warning:
When we give React an array of elements, we also need to help React out by uniquely identifying each element.
Here is how we can fix this issue in our Student Management application:
import StudentCard from './StudentCard';
const data = [
{
id: 'louis-xyz456',
name: 'Louis Dupont',
email: 'louis.dupont@example.fr',
phone: '+33 1 23 45 67 89',
imgLink: '<https://avatar.iran.liara.run/public/31>'
},
// ✂️ Other info trimmed
];
function App() {
return (
<div>
{data.map((info) => (
<StudentCard
imgLink={info.imgLink}
name={info.name}
email={info.email}
phone={info.phone}
/>
))};
</div>
);
}
export default App;
Fortunately, each contact in our data
array has a unique id
. By setting this identifier as the key
, we eliminate the React warning.
The purpose of a key
is to uniquely identify each React element.
More about Keys
So, the previous section we talked about keys at a very high level, in terms of their purpose and why they're necessary.
There's another little mystery with keys. This one is much lower-level.
Take a look at the following JSX:
const element = (
<StudentCard
key: 'anna-abc789',
name: 'Anna Müller',
email: 'anna.mueller@example.de',
phone: '+49 30 12345678',
imgLink: '/images/girl-1.jpg'
/>
);
At first glance, it seems like we've given this component 4 props: key
, name
, email
, phone
and imgLink
. But, if we add a console.log
to this StudentCard
component, we'll notice that something's missing:
function StudentCard({ key, name, email, phone, imgLink }) {
console.log(key); // undefined
console.log(name); // 'Anna Müller'
console.log(email); // 'anna.mueller@example.de'
console.log(phone); // '+49 30 12345678'
console.log(imgLink); // '/images/girl-1.jpg'
return (
<li className="student-card">
{/* ✂️ Removed for brevity */}
</li>
);
}
We've specified 4 props, but only 3 have come through! key
has not been provided.
Here's the deal: there are a small number of “reserved words” in React. key
is one of these special terms. When we apply a key
to a React element, we're not actually setting it as a prop.
Let's dig into this. First, let's take a look at this in plain JavaScript, no JSX:
const element = React.createElement(
StudentCard,
{
key: 'anna-abc789',
name: 'Anna Müller',
email: 'anna.mueller@example.de',
phone: '+49 30 12345678',
imgLink: '/images/girl-1.jpg'
}
);
Hmmm… So far, key
still looks like a prop. Let's keep going.
This code shows that we're calling the React.createElement
function. As the name implies, this function creates a React element. If we were to execute this code, we'd be left with something like this:
const element = {
type: StudentCard,
key:'anna-abc789',
props: {
name:'Anna Müller',
email:'anna.mueller@example.de',
phone: '+49 30 12345678'
}
}
Ah-ha! The React.createElement()
function has taken our data and used it to produce a React element, and that element has key
as a top-level property!
As we saw in the What is React beginner blog post 👀 React elements are JavaScript objects that describe a thing that React needs to create. In this case, the element describes a StudentCard
component that needs to be rendered.
Keys identify a particular React element. It's a property of the element itself, not something that needs to be passed along to the component!
For now, the important thing to understand is this: key
looks like a prop, but it's a special thing that React uses to identify React elements.
Key rules
Let's look at some of the rules that govern how keys should be used.
Top-level element
In order to satisfy this requirement, the key
needs to be applied to the very top-level element within the .map()
call.
For example, this is incorrect:
function NavigationLinks({ links }) {
return (
<ul>
{links.map((item) => (
<li>
<a key={item.id} href={item.href}>
{item.text}
</a>
</li>
))}
</ul>
);
}
From React's perspective, it has a group of <li>
React elements, and it doesn't see any unique identifiers on them. It doesn't "dig in" and look for keys on children elements.
Here's how to fix it:
function NavigationLinks({ links }) {
return (
<ul>
{links.map((item) => (
<li key={item.id}>
<a href={item.href}>{item.text}</a>
</li>
))}
</ul>
);
}
When using fragments 👀 it's sometimes required to switch to the long-form React.Fragment
, so that we can apply the key:
// 🚫 Missing key:
function Thing({ data }) {
return data.map((item) => (
<>
<p>{item.content}</p>
<button>Cancel</button>
</>
));
}
// ✅ Fixed!
function Thing({ data }) {
return data.map((item) => (
<React.Fragment key={item.id}>
<p>{item.content}</p>
<button>Cancel</button>
</React.Fragment>
));
}
Not global
Many developers believe that keys has to be globally unique, across the entire application, but this is a misconception. Keys only have to be unique within their array.
For example, this is totally valid:
function App() {
return (
<ul>
{data.map(contact => (
<StudentCard
key={contact.id}
name={contact.name}
email={contact.email}
/>
))}
{data.map(contact => (
<StudentCard
key={contact.id}
name={contact.name}
email={contact.email}
/>
))}
</ul>
);
}
Each .map()
call produces a separate array, and so there's no problem. 👍
Finally
Effective data iteration in React isn't just about making things work – it's about making them work right. By understanding array mapping, key management, and proper component structuring, you've added essential tools to your React development toolkit. Now go forth and iterate with confidence!
🔍. Similar posts
Simplifying Layouts With React Fragments
18 Jan 2025
Stop Installing Node Modules on Your Docker Host - Install Them in the Container Instead
14 Jan 2025
An Easy to Understand React Component Introduction for Beginners
14 Jan 2025