EN
React - how to use map() method to get index of each element?
2
answers
3
points
How can I use map() method to map some data into components but with getting index of each piece of data?
I have the following array of objects to map into components:
const users = [
{ name: 'Tom', message: "Tom's message" },
{ name: 'Mark', message: "Mark's message" }
];
But I need to map them into table where I need the ordinal number of each element, that's why I'm looking for an index.
2 answers
3
points
Use this construction:
const result = array.map((item, index) => { /* ... */ });
Practical example:
// ONLINE-RUNNER:browser;
// import React from 'react';
const App = () => {
const users = [
{name: 'Tom', message: 'Tom\'s message' },
{name: 'Mark', message: 'Mark\'s message' }
];
return (
<div>
{users.map((item, index) => {
return (
<div key={index}> {/* <--- change key value to some unique id */}
<span>{index}</span> | <span>{item.name}</span> | <span>{item.message}</span>
</div>
);
})}
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
0 comments
Add comment
0
points
You can use map() method with the second argument which is index that can work as ordinal number of each element.
Quick solution:
{users.map((user, index) => (
return (
<TableItem
key={index}
number={index}
name={user.name}
message={user.message}
/>
}
))}
Notes:
- remember that
map()method needs areturnstatement,- each element should have unique
keyproperty.
Practical example
In this example, I'm mapping users array into TableItem components where number argument is an index passed as the map() method second argument.
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines while working React project.
// import React from 'react';
// import ReactDOM from 'react-dom';
// styles for TableItem components
const containerStyle = { display: 'flex', border: '1px solid' };
const childStyle = { flex: 1, padding: '5px' };
// data to map
const users = [
{ name: 'Tom', message: "Tom's message" },
{ name: 'Mark', message: "Mark's message" }
];
const TableItem = ({ number, name, message }) => {
return (
<div style={containerStyle}>
<div style={childStyle}>{number}</div>
<div style={childStyle}>{name}</div>
<div style={childStyle}>{message}</div>
</div>
);
}
const App = () => {
return (
<div>
{users.map((user, index) => (
<TableItem
key={index}
number={index}
name={user.name}
message={user.message}
/>
))}
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );
0 comments
Add comment