9

I have created tabs using React Router, with a different route for each tab. However, I would like to maintain the tab state between tab transitions by keeping the hidden tabs mounted. How do I achieve this? React router remounts each component every time the route switches.

Someone has already asked this question here, but has not received an answer

Ideally I would find a solution which keeps the tabs which are not displayed mounted after they are hit for the first time

kat
  • 5,645
  • 4
  • 19
  • 35
  • 1
    if you want to maintain `state` for several components you would need a parent component that is not re-mounting or a state manager like `redux`. – Sagiv b.g Oct 12 '17 at 16:58
  • 1
    @Sag1v thank you! I would much rather keep track of the component states inside the components themselves, I really just want to leave the components mounted within one session between switching tabs – kat Oct 12 '17 at 17:01
  • i don't think there's a "clean" way of doing it other than the good practice and design pattern of `react` and its tools. maybe you could save it in local storage, but i advice against that. `state` is a memory object that belongs to instance of a `class` (`React.component` class), when you destroy the class you destroy this object. the orthodox approach is to lift the state up to a common parent or save it externally via a state manager like `redux` – Sagiv b.g Oct 12 '17 at 17:09
  • 2
    Did you solve this issue? I'd be very interested in a solution – Unforgiven Jul 15 '20 at 09:57

2 Answers2

1

I'd have to do a little more digging to confirm this actually works, but reading through React Router docs I found this about the Route component. Using the component prop makes the component remount every time the route changes. But using the other render methods, you might be able to achieve what you're looking for. I'd go with render, but children might work too?

cfraser
  • 941
  • 6
  • 16
1

This is the recommended method of routing by react-router-dom-v5 doc over render,children and component prop of <Route/>. This way our component gets re-initialized & re-mounted everytime path is matched.

 <Switch>
    <Route exact path="/">
       <Home />
    </Route>
    <Route path="/contact">
       <Contact />
     Route>
    <Route path="/about">
       <About />
    </Route>
 </Switch>

As you(Kat) want to maintain the tab state between tab transitions by keeping the hidden tabs mounted.

  • you can achieve this by mounting all the tabs at once and then switch between the tabs by using react-router-dom's pathname.
const { pathname } = useLocation();
{pathname === "/"? <Home/>: null}
{pathname === "/contact"? <Contact/>: null}
{pathname === "/about"? <About/>: null}
Firoj Siddiki
  • 1,649
  • 1
  • 20
  • 22