using React I’ve been able to update a value of an object stored in the parent component from a onChange()
made in a child component.
However I’m trying to do the same with a component that is created from a list of mapped objects, so it only updates the value in the object list that built that component. I’m failing but here’s an example of what I’m doing:
Parent Component:
const Parent = () => {
const [banners, bannersUpdate] = React.useState([
{
id: 1, name: "banner1", nameSize: 14
},
{
id: 2, name: "banner2", nameSize: 16
},
{
id: 3, name: "banner3", nameSize: 18
}
]);
const handleUpdateNameSize = (key, e) => {
banners.nameSize = e.value
bannersUpdate({
nameSize: banners.nameSize,
...banners
})
}
return(
<section className="banners">
{banners.map(banner =>
<Banner
key={banner.id}
name={banner.name}
nameSize={banner.nameSize}
updateNameSize={handleUpdateNameSize}
/>
)}
</section>
);
}
Child component:
const Banner = (props) => {
return (
<div className="banCont">
<h2>{props.name}</h2>
<input onChange={(e) => props.updateNameSize(props.key, e.target)} className={'slider1-' + props.name} />
</div>
)
}
With the above it doesn’t update the object item relating to that banner, it instead just adds a new object item at the top level with that name and value.
I believe the answer relies somewhere in using the key
and I’ve tried replacing all the banners
with banners[key]
like: banners[key].nameSize = e.value
but for some reason it’s not working to update the value.
Help would be appreciated please, thanks.