Array iteration using map method and List item key
In this react tutorial, we will create an array in index.jsx, pass this array as attribute to App.jsx component. In App.jsx, we will use map method to create and return a list. Below is the step by step demonstration of how to iterate an array using map method.
Step 1: Create Array
We will create an array arrayNums in index.jsx. Than in render method, we will pass arrayNums as attribute to App.jsx as
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
const array = [4,6,8,2,9];
ReactDOM.render(
<App numbers={array} />
,root);
Step 2: Get array as props
import React from 'react';
const App = (props) => {
const numArray = props.numbers;
}
Step 3: Iterate array using javascript map foreach method
React map method provides a callback arrow function for each element of array while iterating and returns a new array. It has two arguments, first argument is the element of array and second argument is the index count.
import React from 'react';
const App = (props) => {
const arrList = numArray.map(
(num, index) => {
return <li>List item : {num}</li>;
});
return(
<ul>{arrList}</ul>
);
}
export default App;
Step 4: React Key
When you create a list of elements using map method, each element must have a unique key otherwise there is error in browser as below
Key helps react to identify which elements have changed, are removed or are added. Most often IDs from database are used as list item keys. Each key should be unique among its siblings. However, they don’t need to be unique globally as for two different arrays, same keys can be used.
import React from 'react';
const App1 = (props) => {
const numArray = props.numbers;
(num, index) => {
return <li key={index}>List item : {num}</li>;
});
return(
<ul>{arrList}</ul>
);
}
export default App1;
Post a Comment