Search code examples
arraysreactjsstatejavascript-objectsreact-hooks

How to render a React Hook State whose type is an Array of Objects?


I am trying to render the array of objects stored in a React Hook state, which stores the names and numbers for a phonebook:

const App = () => {
  const [ persons, setPersons] = useState([
    { name: 'Arto Hellas', number: '000-000-0000' },
    { name: 'Ada Lovelace', number: '39-44-5323523' },
    { name: 'Dan Abramov', number: '12-43-234345' },
    { name: 'Mary Poppendieck', number: '39-23-6423122' }
  ]); 

  return (
    <div>
      <h2>Phonebook</h2>
      <div>{persons}</div>
    </div>
  )
}

However I get the following error:

Objects are not valid as a React child (found: object with keys {name, number}). If you meant to render a collection of children, use an array instead.

I've tried the following:

I thought by creating <div> for each index of the array, I can render each individually, rather than rendering the whole array at once, but that does not seem to be the issue.

const App = () => {
  const [ persons, setPersons] = useState([
    { name: 'Arto Hellas', number: '000-000-0000' },
    { name: 'Ada Lovelace', number: '39-44-5323523' },
    { name: 'Dan Abramov', number: '12-43-234345' },
    { name: 'Mary Poppendieck', number: '39-23-6423122' }
  ]); 

  return (
    <div>
      <h2>Phonebook</h2>
      <div>{persons.map(person => <div> {person} </div>)}</div>
    </div>
  )
}

But when I try that, I get the same error message.

How can I render the objects in the state?


Solution

  • You're still trying to render an object. You need to access it's properties

    const App = () => {
      const [ persons, setPersons] = useState([
        { name: 'Arto Hellas', number: '000-000-0000' },
        { name: 'Ada Lovelace', number: '39-44-5323523' },
        { name: 'Dan Abramov', number: '12-43-234345' },
        { name: 'Mary Poppendieck', number: '39-23-6423122' }
      ]); 
    
      return (
        <div>
          <h2>Phonebook</h2>
          <div>{persons.map(person => <div key={person.name}> {person.name} </div>)}</div>
        </div>
      )
    }