Mapping Out Information with React

In React it’s very easy (and quick!) to get basic information rendered to a page. Let’s say we have a ‘dog’ object and we want some of the info for that dog displayed on the screen.

const dog = {name: 'Boog', age: 6, breed: 'Australian Sheppard'}*** <Dog name={dog.name} age={dog.age} breed={dog.breed} />const Dog = () => {  return(
<div>
<h1> {props.name} </h1>
<h2> {props.age} </h2>
<h2> {props.breed} </h2>
</div>
)
}

*If the ‘dog’ object exists on the level higher than the ‘Dog” component, we can pass the information through as props like we have written.

Now what we would do if instead of being supplied ‘dog’ to render out, we get ‘dogs’ like this?

const dogs = [
{name: 'Boog', age: 6, breed: 'Australian Sheppard'},
{name: 'Peppers', age: 10, breed: 'English Pointer'},
{name: 'Oscar', age: 7, breed: 'English Pointer'},
{name: 'Tasha', age: 13, breed: 'Weimaraner'}
]

We wouldn’t really want to take the time to go through that like this would we?

<Dog name={dog[0].name} age={dog[0].age} breed={dog[0].breed} />
<Dog name={dog[1].name} age={dog[1].age} breed={dog[1].breed} />
<Dog name={dog[2].name} age={dog[2].age} breed={dog[2].breed} />
<Dog name={dog[3].name} age={dog[3].age} breed={dog[3].breed} />

And what if our app needed to reflect an array of dogs that changes, if the dog array gained two new pups how would we render them out? We can use ‘map’ on the array to get them all on screen!

When dealing with a situation where I need to render out an array of objects to keep things organized, I like to create a two components. First is the container component that will hold the array and the map function (DogsContainer). Second is the component that will receive props and reflect an individual from the array (Dog). The two components will be this.

const DogsContainer = () => { const dogs = [
{name: 'Boog', age: 6, breed: 'Australian Sheppard'},
{name: 'Peppers', age: 10, breed: 'English Pointer'},
{name: 'Oscar', age: 7, breed: 'English Pointer'},
{name: 'Tasha', age: 13, breed: 'Weimaraner'}
]
const appendDogs = () => {
return dogs.map(d => <Dog dog={d}/>)
}
return(
<>
{appendDogs()}
</>
)
}

const Dog = ({dog}) => {
return(
<div>
<h1> {dog.name} </h1>
<h2> {dog.breed} </h2>
<h2> {dog.age} </h2>
</div>
)
}

Here we are creating a function called ‘appendDogs’ which is mapping through the dogs array and creating a new ‘Dog’ component for each dog in that array. As props we are passing the entire dog object through. In the ‘Dog’ component we are destructuring the props so we don’t need to write ‘props.dog…’ and can simply access our dog object by typing ‘dog’. Each time the map loop is run we are creating a complete complete with all the info we want about each individual dog and we get all of them on screen. Best of all, if that ‘dogs’ array gains a few more dogs it’ll still work!