lorenzoli
lorenzoli

Reputation: 55

React hook - HowTo pass state to child components

I have the following scenario: i have react hooks for take a snapshot of an object called fruit and pass this to my child components.

I want to update the fruit snapshot object when i change something via an input and pass this updated snapshot object to my child component.

This is an example of my fruit object

const fruit = {
    id: 1,
    fruit_name: 'apple'
}

This is my ParentComponent code

const ParentComponent = props => {
    const [fruit, setFruit] = useState(props.currentFruit);

    // Take snapshot of fruit
    useEffect(() => {
        if (fruit.id !== props.currentFruit.id) {
            setFruit(props.currentFruit)
        }
    })

    // Save changes to snapshot fruit
    const changed = event => {
        const prevFruit = fruit;
        prevFruit[event.target.name] = event.target.value;

        setFruit(prevFruit);

        console.log(fruit);
        // Here it seems changed !
    }

    return (
        <ChildComponent fruit={fruit} changed={event => {changed(event)} />
    )

}

And this is my ChildComponent code

const ChildComponent = props => (
    <input
        type="text"
        name='fruit_name'
        value={props.fruit.fruit_name}
        onChange={props.changed}  />
)

What is it bad ? Is it possible to change state and pass to children components ? Is it a good approach ?

Thanks for help in advanced !

Upvotes: 0

Views: 735

Answers (1)

mattp94
mattp94

Reputation: 36

In your example, you directly mutate fruit before passing it to setFruit, so it keeps the same reference. You have to pass a new object containing your change. In your case:

setFruit({
  ...prevFruit,
  [event.target.name]: event.target.value,
});

Upvotes: 2

Related Questions