Im rendering an array of objects, then I'm trying to add a new property to it via a function, but that new property value does not render. When I console log the object I can see that the property and the new value are there. That new property is tag. I assume this has something to do with e.preventDefault()
. How can I fix this?
const addTag = (e,id) => {
e.preventDefault()
let text = e.target.tag.value
let obj = stu.find(x => x.id === id)
obj.tag = text
console.log(obj)
}
return (
<div className="App">
{stu.map((student, id) => (
<div key={id}>
<p>{student.email}</p>
<p>{student.firstName}</p>
<p>{student.tag}</p>
<form onSubmit={(e) => addTag(e, student.id)}>
<input type="text" id="tag"/>
<button type="submit">Submit</button>
</form>
</div>
))}
</div>
);
}
CodePudding user response:
Your state variable is an array. Modifying objects in that array, (or even adding/removing elements entirely) will not cause react to re-render. The reference to the array must change. One easy way to do this is to copy the elements to a new array:
const addTag = (e,id) => {
e.preventDefault()
let text = e.target.tag.value
let obj = stu.find(x => x.id === id)
obj.tag = text
setStu([...stu])
}
*you may run into issues since you're keying only on the element index. Consider changing your key value as well
CodePudding user response:
I assume, student is a state and you need to update it after adding tag.
const addTag = (e,id) => {
e.preventDefault()
let text = e.target.tag.value
let obj = stu.find(x => x.id === id)
obj.tag = text
console.log(obj)
setStu([...stu])
}