Home > Mobile >  React Hooks: Update useState hook from a different .jsx file?
React Hooks: Update useState hook from a different .jsx file?

Time:11-05

I have two components, each in their own file, that I would really like to keep separate, as the second one is reusable. However, I need to be able to update one of the hooks within the "child" component from the "parent" component. I have tried by passing in a value as a prop, but this won't actually set the value back to 0. I'm not even sure it does anything.

To be more specific, I am using a Material UI Tabs component in the child component, and would like to update the Tabpanel's "value" through the use of props from the parent component.

Here is an example code sandbox that has the same issue.

To see the problem:

Type and select "vegetables" and then click on the second tab, "artichokes." If you click on the search bar again and then select "fruits", the tab value will still be at "1" and thus the component will show nothing until you manually click on the "strawberries" tab.

You'll also get this error:

MUI: The value provided to the Tabs component is invalid. None of the Tabs' children match with "1". You can provide one of the following values: 0.

CodePudding user response:

I see two solutions for your problem.

  1. I would add key tag to your component as below:
    <Food key={selectedFood} desiredFood={selectedFood} val={0} />

It will rerender your Food component with new props on selectedFood change.

  1. More brutal - just use react hook - useEffect - i would not recommend it but you can add in your Food method this hook and set dependency array to selectedFood

      useEffect(() => {
         console.log("render");
         setValue(0);
       }, [props.desiredFood]);
    

It's just something quick that came into my mind and if i will think about better idea, i will share it.

Both solutions will rerender Food component on every selectedFood val change.

Here is my fork with working solutions i hope.

  • Related