Raj
Raj

Reputation: 4079

How to render a list of objects using React

[{"id":8,"name":"christoph","age":32,"number":"555-555-5555"},
{"id":9,"name":"debra","age":31,"number":"555-555-5555"},
{"id":10,"name":"eric","age":29,"number":"555-555-5555"},
{"id":19,"name":"richard","age":20,"number":"555-555-5555"},
{"id":14,"name":"santiago","age":25,"number":"(555)555-5555"}]

Backend dev here. (making a quick and scrappy project so please forgive me for asking a n00b question)

I need to render this using React in a Table format.

I looked at some examples like this codepen but it didn't help. Can anyone guide me to a Codepen or a starter prooject that I could look into to get this done? I am not able to figure out how to map over the objects of the array.

Upvotes: 1

Views: 1655

Answers (1)

Olivier.C
Olivier.C

Reputation: 181

You can refer you to the documentation of React.JS thought this link

But for your case, if you want to render an array of object as a table you can do this using map array prototype in jsx.

const persons = [
  { id: 8, name: "christoph", age: 32, number: "555-555-5555" },
  { id: 9, name: "debra", age: 31, number: "555-555-5555" },
  { id: 10, name: "eric", age: 29, number: "555-555-5555" },
  { id: 19, name: "richard", age: 20, number: "555-555-5555" },
  { id: 14, name: "santiago", age: 25, number: "(555)555-5555" },
]

return (
  <table class="table">
    <thead>
      <tr>
        <th scope="col">#</th>
        <th scope="col">Name</th>
        <th scope="col">Age</th>
        <th scope="col">Number</th>
      </tr>
    </thead>
    <tbody>
      {persons.map(person => (
        <tr key={person.id}>
          <th scope="row">{person.id}</th>
          <td>{person.name}</td>
          <td>{person.age}</td>
          <td>{person.number}</td>
        </tr>
      ))}
    </tbody>
  </table>
)

I think this should work.

Upvotes: 2

Related Questions