Dana Dana - 4 months ago 83
React JSX Question

ActiveClassName with multi-tiered tabs in react-router

React-Router doesn't recognize components for nested routes if they're different from their parent route, but the alternative keeps activeClassName in Link from working as intended.

I have a site with the following multi-tiered tab layout:

+---------+---------+
| Tab 1 | Tab 2 |
+ +---------+---------------------------+--------+--------+
| | Menu 1 | Menu 2 |
+-----------------------------------------------+ +--------+
| |
~ ~


My routes are defined as follows:

<Router history={browserHistory}>
<Route path"/" component={App}>
<Route path="Tab1" component={Tab1Component}>
<Route path="Menu1" component={Tab1Component} />
<Route path="Menu2" component={Tab1Menu2Component} />
</Route>
<Route path="Tab2" component={Tab2Component} />
</Route>
</Router>


The tab links are defined as follows:

<Link to="/Tab1/Menu1" activeClassName="active" />
<Link to="/Tab2" activeClassName="active" />


And the menu links are defined as follows:

<Link to="/Tab1/Menu1" activeClassName="active" />
<Link to="/Tab1/Menu2" activeClassName="active" />


When I click on "Tab 1", then "Menu 2", the active class is still applied to "Tab 1" and "Menu 2" (as they should), but the Tab1Component is still displayed. If I move the Tab1Menu2Component route outside its parent...

<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="Tab1" component={Tab1Component}>
<Route path="Menu1" component={Tab1Component} />
</Route>
<Route path="Tab1/Menu2" component={Tab1Menu2Component} />
<Route path="Tab2" component={Tab2Component} />
</Route>
</Router>


...then the Tab1Menu2Component content is displayed when I click on "Menu 2". BUT, then you can't use the activeClassName in a manner such that "Tab 1" and "Menu 2" both get the active class... "Menu 2" steals the active class from "Tab 1".

I want to do this in a way that both Tab1 and Menu2 can simultaneously have the active class and the Tab1Menu2Component is displayed. How do I accomplish this?

Answer

You could simply return this.props.children from Tab1Component.

I suggest you refer the dynamic segments example found in react-router repository. It pretty much deals with similar scenario