map()
takes an array manipulates the array and returns a new array of the manipulated data.
Using the map()
array method in React is the standard for React apps.
In the example below there is some hard coded state called doggos which is an array of objects. Obviously in a proper app the state likely would of come from a database and not hard-coded data.
import React, { useState } from "react"
export const App = () => {
const [doggos] = useState([
{ name: "Spike" },
{ name: "Winston" },
{ name: "Shandy" },
{ name: "Fluffy" },
])
return (
<div>
<ul>
{doggos.map(dog => (
<li key={dog.name}>{dog.name}</li>
))}
</ul>
</div>
)
}
export default App
In the example it takes the doggos array and for each dog returns the dog name as a <li>
. You can see this as <li key={dog.name}>{dog.name}</li>
. You'll notice a key is added to each list item key={dog.name}
. This is because each list item requires and individual key property in React. For the key value use something you know will be individual like an ID. There are helpful libraries out there such as uuid which can help for this.
Top comments (0)