Search code examples
javascriptarraysreactjsuse-state

Why is my page not updating with the addition of an element to my array when using React


I am working on a basic react app where I use a form to submit a person's name then it will show up on the screen. After inputting the name, the array does properly get updated, but nothing changes on the screen. This is what I am using to show the person's name. In this case, I have useState on persons so I thought it should update. I am still quite new to React so any help is appreciated. Thanks in advance

{persons.map(person =>
    <div key={person}>{person.name}</div>
}

Edit:

const [persons, setPersons] = useState([
     { name: 'Arto Hellas' }
]) 
const [newName, setNewName] = useState('')

const addPerson = (event) => {
     event.preventDefault()
     setPersons(persons.concat(newName))
     setNewName('')
}

Solution

  • const [persons, setPersons] = useState([
         { name: 'Arto Hellas' }
    ]) 
    const [newName, setNewName] = useState('')
    
    const addPerson = (event) => {
         event.preventDefault()
         setPersons([...persons,{name:newName}])
         setNewName('')
    }