DEV Community

sam-a-code
sam-a-code

Posted on

Mapping in React

Something I've learned recently is how to map in React. Below I'll walk through one example of how to set up mapping in a React app.

1. Set up your parent component

Identify the component that should contain the data you fetch. This will likely be a parent component – make sure to think about which child components need access to the data! You'll be passing the data to those components as props.

In this example, we'll pull a list of resources (the data), map the data, create cards for each resource, and then pass the data to a separate component as props to format the cards. The parent component is called ResourceList and the child is ResourceCard.

import React, {useState, useEffect} from "react";
import ResourceCard from "./ResourceCard";

function ResourceList() {
  const [resources, setResources] = useState([])

  useEffect(() => {
    fetch('http://localhost:3000/resources')
    .then((r) => r.json())
    .then((resources) => setResources(resources))
    }, [])

  const resourceList = resources.map((resource) => {
    return (
      <ResourceCard
      key={resource.id}
      name={resource.name}
      url={resource.url}
      summary={resource.summary}
      image={resource.image}
        />
    ) })

  return (
    <div>
      <h2>Resources</h2>
      <ul>
        {resourceList}
      </ul>
    </div>
  )
}

export default ResourceList;


Enter fullscreen mode Exit fullscreen mode

Let's break down that code.

First, we import React, useState, and useEffect from "react". We also import our ResourceCard since we need to include it in our ResourceList return.

Then, we set up our ResourceList function. Within that, we start with creating state for our data – using an empty array so the data we fetch has somewhere to go!

Next is our useEffect function. We pull our data from /resources, convert it to json, and then set our resources. We include an empty array at the end of the function so that this fetch only happens once, when the page loads.

Now we get to map our data! We put it in a new variable (resourceList) and set it equal to our mapping method. Note that this resourceList is different than our ResourceList. While they have almost the exact same name, components in React start with capital letters and variables use camelcase (at least as a best practice!). What we're saying with this method is: create a ResourceCard for every resource in the resources list.

We've also made sure to include the parameters we'll need to pass down to ResourceCard (key, name, url, summary, image). This can also be accomplished by using a spread operator, but I like writing it all out because it's easier for my brain to see all of the parameters listed individually.

Below our mapping function we set up our return for ResourceList. We wrap everything in one <div>, then within that <div> we set up <h2> and <ul> elements. The <h2> will hold our title and the <ul> will contain our {resourceList} (the bit we just mapped above!).

Finally, we write export default ResourceList so our App.js can import it!

2. Set up your child component

In this instance, our child component is pretty simple! We just have to set up the JSX for our ResourceCard.

import React from 'react';

function ResourceCard({summary, name, url, image}) {
    return (
        <div>
            <img src={image}/>
            <h2>{name}</h2>
            <p>{summary}</p>
            <a href={url} target="_blank">Read more!</a>
        </div>
    )
}

export default ResourceCard;

Enter fullscreen mode Exit fullscreen mode

We'll break the code of this component down as well:

We start off by importing React from 'react', of course.

Then, we set up our ResourceCard function. This function won't work if we don't accept the parameters being passed down from ResourceList. By including {summary, name, url, image} in this function, we are facilitating the data flow between the parent and child components.

The ResourceCard return sets up how we want our mapped data displayed. Again, we set up a <div> to contain everything. Within that <div>, we create elements for our {image}, {name}, {summary}, and {url} data points.

Finally, we write export default ResourceCard so that ResourceList can import it. Our data is now mapped and rendering on individual cards for each resource.

Hopefully this was a helpful overview of mapping data and passing it between components! One note – I removed all className references so that this example was easier to read, but of course I'd recommend styling your cards once they're mapped. It's half the fun – at least for me!

Top comments (0)