0

I have to make nested router in react 4 like react 3 following is my code of App.js

import React, { Component } from 'react';
import './App.css';

import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import history from './history';

import Home from './components/root/home/Home';
import Root from './components/root/Root';
import Headers from './header/Header';
import Footer from './footer/Footer';

class App extends Component {
  render() {
    return (
      <div className="app-component">
        <Router history={history}>
          <Route exact path={"/"} component={Root}>
            <Route path={"/index"} component={Home} />
          </Route>
        </Router>
       <Headers />
        {this.props.children}
       <Footer />
      </div>
    );
  }
}


export default App;

what is wrong with code I have to make nested router in react 4 like react 3

1 Answers1

0

Do not nest Route component inside another Route component instead add the nested Route inside the component where you want it to render.
eg:

 class App extends Component {
      render() {
        return (
          <div className="app-component">
            <Router>
              // using path="/" will throw an error
              <Route path="/root" component={Root} />
            </Router>       
           <Headers />
            {this.props.children} 
           <Footer />
          </div>
        );
      }
    }

function Root({match}) {
  return (
    <div>
      <h2>Root</h2>
      <ul>
        <li>
          <Link to={`${match.url}/home`}>Home</Link>
        </li>
      </ul>
      <Route path={`${match.path}/:nestedComponent`} component={Home} />
    </div>
  );
}

For more information about nesting routes, you should go through this Source

Sahil Raj Thapa
  • 2,353
  • 3
  • 12
  • 23