Map method in React.

ham_codes
2 min readJan 10, 2021

There are many things you can do with JavaScript. One of the methods I have seen most frequent is the map method. Simply explained by mdn, “The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.” How do we use this in React? In React there are usually many files and components and information flowing from different places. As an easy example for me to explain, I will use a small React app as an example of how someone can map over a list that is already populated. Let’s look at a React app with four main files we will be working with. In the main directory we have our index.js and info.js. In the components folder we have an App.jsx and an Entry.jsx. Inside of our index.js will be the import statements for React, ReactDOM and APP. We will do a ReactDOM.render to show what is in our App.jsx.

Index.js:

import React from “react”;import ReactDOM from “react-dom”;import App from “./components/App”;ReactDOM.render(<App />, document.getElementById(“root”));

The info.js file contains four objects within an array that hold information that we want to map through. This looks like the following:

Info.js

const info = [{id: 1,name: "Jeremy",mood:"Happy"},{id: 2,name: "Steve",mood:"Sad"},{id: 3,name: "Katie",mood:"Cheerful"},{id: 4,name: "Erin",mood:"Goofy"}];export default info;

Inside our App.jsx file we need to import React but also create a function that will create each Entry that we want to show on screen. This can be done in the following way.

App.jsx

import React from "react";import Entry from "./Entry";import info from "../info";function createEntry(data) {return (<Entrykey={data.id}name={data.name}mood={data.mood}/>);}function App() {return (<div><dl>{info.map(createEntry)}</dl></div>);}export default App;

Having the createEntry function set in this way, we can now go into our Entry.jsx and pass props. This will look as follows:

Entry.jsx

import React from "react";function Entry(props) {return (<div><dt><span>{props.name}</span><br /><span>{props.mood}</span></dt></div>);}export default Entry;

This may be a simplistic explanation of everything going on here but this is a small example of the power of the map method in JavaScript. Thanks for reading!

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

--

--