Search code examples
reactjsdropdown

How to maintain dropdown option value even after switching between components in reactjs?


So basically i have two tab view or 2 tabs. The first tab has multiple dropdowns and the second dropdown have nothing .So if i select values from the tab which has dropdowns and switch to the second tab the values which i have selected is gone . Basically the state is not being maintained .

My issue is how to maintain the state or the values of the selected dropdowns even if i switch between tabs

With basic reactjs solution no redux or hooks.


Solution

  • What you're describing is a problem global state solutions such as redux solve. Since you'd like to use a vanilla react solution I'd suggest either lifting the state to the parent of both components or using Context API - you can read about Context here: https://reactjs.org/docs/context.html#reactcreatecontext

    Lifting state up basically means moving the place you declare state and the function that changes state up to the parent of both components. Then you can pass down the state and the function that changes state as props allowing both components to share that state as well as have the ability to change state.

    If this is just a small amount of data or something simple I'd go with lifting state up. If it's going to grow over time I'd use Context.

    Good luck!