Search code examples
reactjsreact-routerreact-router-domreact-router-reduxreact-router-component

React nested routing not working properly


I am creating Frontend for Django application. I want to route my app component into following.

/
/dashboard
/about
/contact

then the dashboard component should route as

/dashboard/
/dashboard/notification/
/dashboard/profile/

I successfully routed my App component as

import React, { Component, Fragment } from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom'
import HomeMain from './layout/main/HomeMain'
import './css/style.css'
import Notfound from './layout/main/Notfound'
import Dashboard from './layout/dashboard/Dashboard'
class App extends Component {
  render() {
    return (
      <Router>
        <Fragment>
          <Switch>
            <Route exact path="/dashboard" component={Dashboard} />
            <Route exact path="/" component={HomeMain} />
            <Route exact path="/not" component={Notfound} />
          </Switch>
        </Fragment>
      </Router>
    )
  }
}
ReactDOM.render(<App />, document.getElementById('app'))

Then I tried nested routing for routing my dashboard but the output becomes a blank page at http://127.0.0.1:8000/dashboard/notification/

import React, { Fragment } from 'react'
import '../../css/dash.css'
import '../../css/style.css'
import DashHeader from './DashHeader'
import DashMain from './Dmain/DashMain'
import NotiMain from './Dmain/NotiMain'
import { Switch, Route, BrowserRouter as Router } from 'react-router-dom'
class Dashboard extends React.Component {
  path = this.props.match.path

  render() {
    return (
      <Fragment>
        <DashHeader />
        <Switch>
          <Route exact path={`${this.path}/`}>
            <DashMain />
          </Route>
          <Route exact path={`${this.props.match.url}/notification`}>
            <DashMain />
          </Route>
        </Switch>
      </Fragment>
    )
  }
}
export default Dashboard

Solution

  • You need to remove exact from /dashboard route when Dashboard component has children (nested) routes:

    <Router>
        <Fragment>
            <Switch>
                <Route path="/dashboard" component={Dashboard}/> // remove exact
                <Route exact path="/" component={HomeMain}/>
                <Route exact path="/not" component={Notfound}/>
            </Switch>
        </Fragment>
    </Router>
    

    From docs:

    When true, will only match if the path matches the location.pathname exactly.

    So, when you add exact at /dashboard and hit /dashboard/some-child-route in browser, it doesn't match with Dashboard route and doesn't render it and its children.

    This post will also help you understand it.