map()
is a JavaScript function commonly used in ReactJS. It is used to traverse a list or array and create a new one. The function allows us to visit each array element and perform the required actions.
The map()
function transforms an array of data into an array of React elements that can then be rendered as part of map()
function on it. The map()
function will traverse each element individually.
Note:
map()
functions are also used instead of loops in ReactJS, as loops cannot be implemented insidereturn()
in the ReactJS code.
For better understanding, we will take the following code as an example:
import React from 'react'; require('./style.css'); import ReactDOM from 'react-dom'; import App from './app.js'; ReactDOM.render( <App />, document.getElementById('root') );
Line 3–7: An array, employees
, of employees' data.
Line 9–23: The EmployeeList()
function is responsible for creating the front-end. It takes the employee
array as an argument.
Line 14: The map()
function is implemented on the employees
array. The employee
parameter will be used to traverse each element of the array.
Line 15–17: The employee
parameter uses the keys of each array element to render their values.
Line 25–31: The App()
function calls the EmployeeList()
function.
Free Resources