A quick look displaying data in React with Hooks and map()

davidbell_xyz

David Bell

Posted on October 21, 2020

A quick look displaying data in React with Hooks and map()

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
Enter fullscreen mode Exit fullscreen mode

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.

Let's connect

Twitter

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
davidbell_xyz
David Bell

Posted on October 21, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About