Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain state between routes with React Router?

My application had a tab component with 4 tabs. The content of each tab was set up as a separate component. I'm replacing the tab with 4 different routes. I got rid of the tab and used react-router to set up 4 routes, one for each of the 4 components.

The content of a tab would maintain its state when navigating to and from the tab. For example, say the user has scrolled to the bottom of a list in one tab. If the user navigates to a different tab and comes back, the list would remain scrolled to the bottom.

I'm not able to achieve this behavior with routes. I noticed that when I navigate from one route to another, the components are re-instantiated (not just re-rendered).

I want to achieve the tab-like behavior. I know that there's a library called UI-Router-Extras for Angular that provides deep state redirect. But I can't find a similar option for React. I have tried react-router and react-router-component and both re-instantiate a component when its route becomes active.

Is there a solution to achieve this behavior for routes in React?

like image 508
DFB Avatar asked May 21 '16 11:05

DFB


1 Answers

Personally, I chose to ditch react-router in this case and create a parent component with a state containing the current tab to display, while only displaying the active one.

Here's a very simple example

    <div
      style={{display: this.state.currentTab === 'component_a' ? 'block' : 'none'}}
    >
      <ComponentA />
    </div>
    <div
      style={{display: this.state.currentTab === 'component_b' ? 'block' : 'none'}}
    >
      <ComponentB />
    </div>
like image 160
Elie Zgala Avatar answered Sep 22 '22 09:09

Elie Zgala