Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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('')
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

const addPerson = (event) => {
     event.preventDefault()
     setPersons([...persons,{name:newName}])
     setNewName('')
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading