React-Router: Handling Deeply Nested Routes with Class Components

  javascript, react-router, reactjs

Trying to figure out how to navigate through deeply nested class component routes, and I’m a bit lost as to how to do it correctly.

So here’s the general architecture of the components:

--Component L
  |_Component L1
  |_Component L2

--Component S (accessible after authentication)
  |_Component S1
    |_Component S1.1
      |_Component S1.1.1
      |_Component S1.1.2
  |_Component S2
    |_Component S2.1 
    |_Component S2.2
    |_Component S2.3
      |_Component S2.3.1
  |_Component S3
    |_Component S3.1

And technically the nested components may go much deeper than what’s shown. The general idea is that components L and S are parental containers (or anchors) for smaller components; components such as S1, S2, and S3 are components of different categories, and there are more components under each category. At all time the top-most component S is visible and provides buttons/tabs to navigate to one of the components S1, S2, and S3, which should be drawn inside a canvas div in component S. Only the content in this canvas div should be updated with each route change.

Currently, to navigate between L and S, I have the following Switch set up:

<Switch>
    <Route to='/L' component={L} />
    <AuthRoute to='/S' component={S} />
</Switch>

and component S looks roughly like this:

export default class S extends Component {
    <Menu>
        <Button>to S1</Button>
        <Button>to S2</Button>
        <Button>to S3</Button>
    </ Menu>
    <div>
        <Content >
            Child components should be drawn in here.
        <Content />
    </ div>
}

The documentation demonstrates an example using useRouteMatch(), but that is only available inside functional components.
How can this be done with class components?

Source: Ask Javascript Questions

LEAVE A COMMENT