ReactJs create Router inside another Router

React Router is used to keep UI in sync with the URL. React Router from this we can get the router usage and syntax. But we can’t get the logic of the usage from anywhere.

Here I will explain how to use route inside another route.
For Example, I have two tab container.
1. Menu tab (Tab1, Tab2, Tab3)
2. Submenu Tab (STab1, STab2, STab3, STab4)
Now, i want to create a single page like inside the Main tab “Tab2”, i need Submenu tabs. but whenever i refreshed the page i want the same opened tab again. How?

Solution:
First we will create Main Tab with React Router.

// include lib files
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/2.4.1/ReactRouter.min.js"></script>
ReactDOM.render((
        <Router>
            <Route path="/" component={TabLayout}>
                <IndexRedirect to="/tab1" />
                <Route path="tab1" component={tab1} />
                <Route path="tab2" component={tab2} />
                                <Route path="tab3" component={tab3} />
            </Route>
        </Router>
    ), document.getElementById('myApp'));
 

Now the Main Tab router created. Now we want to create Submenu router only inside of “Tab2”.

ReactDOM.render((
        <Router>
            <Route path="/" component={TabLayout}>
                <IndexRedirect to="/tab1" />
                <Route path="tab1" component={tab1} />
                <Route path="tab2" component={tab2}>
                                <IndexRedirect to="/tab2/subtab1" />
                                                <Route path="tab2/subtab1" component={stab1} />
                                                <Route path="tab2/subtab2" component={stab2} />
                                                <Route path="tab2/subtab3" component={stab3} />
                                                <Route path="tab2/subtab4" component={stab4} />
                                </Route>
                                <Route path="tab3" component={tab3} />
            </Route>
        </Router>
    ), document.getElementById('myApp'));
 

Leave a Reply

Your email address will not be published. Required fields are marked *