handsome
handsome

Reputation: 2422

update state from a child component

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

Answers (2)

Vishnu
Vishnu

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

Darshan Chauhan
Darshan Chauhan

Reputation: 1

Check this Solution

Sending the Parent State as A Prop of Child Component Using a Prop Method to Handle State Update

Upvotes: 0

Related Questions