Borislav Hadzhiev
Fri Apr 22 2022·2 min read
Photo by Freddy Kearney
To use the map() method with index in React:
map()
method on the array.map()
method gets called with the element and
index.export default function App() { const employees = [ {id: 1, name: 'Alice', salary: 100}, {id: 2, name: 'Bob', salary: 75}, {id: 3, name: 'Carl', salary: 125}, ]; return ( <div> {employees.map((employee, index) => { return ( <div key={index}> <h2>Index: {index}</h2> <h2>Name: {employee.name}</h2> <h2>Salary: {employee.salary}</h2> <hr /> </div> ); })} </div> ); }
The function we passed to the Array.map method gets called with each element in the array and the index of the current iteration.
On each iteration, we render the index
and the name
and salary
properties
on the employee
object.
Notice that when calling the map()
method inside of our JSX code, we have to
use curly braces {}
to wrap the call to map()
.
We used the index
for the key
prop in the examples, however it's better to
use a stable unique identifier if you have one. We could have used the id
property on each object.
The key
prop is used internally by React for performance reasons. It helps the
library make sure to only re-render the array elements that have changed.
We used an arrow function with an explicit return statement in the example. If you only need to render some JSX elements and don't use conditions, declare variables, etc, you can use an implicit return, which would make your code a little more readable.
export default function App() { const employees = [ {id: 1, name: 'Alice', salary: 100}, {id: 2, name: 'Bob', salary: 75}, {id: 3, name: 'Carl', salary: 125}, ]; return ( <div> {employees.map((employee, index) => ( <div key={index}> <h2>Index: {index}</h2> <h2>Name: {employee.name}</h2> <h2>Salary: {employee.salary}</h2> <hr /> </div> ))} </div> ); }
We used implicit returns for the arrow function we passed to the map()
method.
const arr = ['a', 'b', 'c']; // 👇️ explicit return const result1 = arr.map(element => { return element; }); // 👇️ implicit return const result2 = arr.map(element => element);
You can only use implicit returns when you don't have to use conditionals or
define variables in the function you pass to map()
.