10

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?

Yves Gurcan
  • 1,096
  • 1
  • 10
  • 25
DFB
  • 861
  • 10
  • 25

2 Answers2

1

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>
Elie Zgala
  • 145
  • 2
  • 9
0

You have two options, use Redux, or show/hide components based on tabs.

Heres an example to show/hide components

{this.state.showAboutMe ? <AboutMeComponent navigation={this.props.navigation} props={this.props.user} /> : undefined}
Gavin Thomas
  • 1,827
  • 2
  • 11
  • 17