Reputation: 2422
I can´t wrap my head around this. I want to update the state from within a child component
const Main = () => {
const [brands] = useState([{ name: "John", age: 20 }, { name: "Mary", age: 10 }]);
return brands.map(brand => <Child brand={ brand } />)
}
const Child = (props) => {
const { age } = props.brand;
return <button onClick={ "how to update age here and make it available in the parent component" } />
}
Upvotes: 0
Views: 52
Reputation: 1701
useState hook returns the state and as well as a function to set that state. You could pass this setter to the child component and call from there.
const Main = () => {
const [brands, setBrands] = useState([{ name: "John", age: 20 }, { name: "Mary", age: 10 }]);
const updateState = (brand, indexToUpdate) => {
const newState = [...brands];
newState[indexToUpdate] = brand;
setBrands(newState);
};
return brands.map((brand, idx) => <Child brand={ brand } updateState} idx={idx} />)
}
const Child = (props) => {
const { age } = props.brand;
return <button onClick={() => props.setBrands(props.brand, props.idx) } />
}
Upvotes: 1
Reputation: 1
Sending the Parent State as A Prop of Child Component Using a Prop Method to Handle State Update
Upvotes: 0