1

I'm trying to access to sub components with nested routing in React using react-router-dom 5.2.0. Here you can find a CodeSandbox link of the project: https://codesandbox.io/s/nested-routes-8c7wq?file=/src/App.js

First, let me show you the tree structure of my pages.

  • Home
  • About
  • Organisations
    • MainContent
    • SecondContent

Routes for main pages (Home, About, Organizations) are in src/routes folder. So their link look like:

  • https://localhost:3000/ (for Home)
  • https://localhost:3000/about (for About)
  • https://localhost:3000/organizations (for Organizations)

At this point, everything is okay for me. The problem is with the nesting part..

On Organizations page, I have to be able to switch between MainContent and SecondContent. So links into that page must look like this:

But I cannot print any of those contents...

ParkerIndustries
  • 171
  • 2
  • 15

1 Answers1

1

If you want to build nested paths you should use the path and url from the current route match and build the nested routes and links from there.

src/pages/Orgainizations

import { Switch, Route, useRouteMatch } from "react-router-dom";

const Organizations = (props) => {
  const { path, url } = useRouteMatch(); // <-- get current path and url
  const [value, setValue] = useState("");

  const menuLinks = {
    data: [
      {
        id: 0, // <-- fix React key issue in NavBar
        title: "StackOverflow",
        to: `${url}/maincontent` // <-- build nested link
      },
      {
        id: 1, // <-- fix React key issue in NavBar
        title: "BitBucket",
        to: `${url}/secondcontent` // <-- build nested link
      }
    ]
  };

  return (
    <div>
      <NavBar changeValue={(value) => setValue(value)} menuLinks={menuLinks} />
      <div>
        <Switch>
          <Route
            render={() => <MainContent title={value} />} // *
            exact
            path={`${path}/maincontent`} // <-- build nested path
            strict
          />
          <Route
            render={() => <SecondContent title={value} />} // *
            exact
            path={`${path}/secondcontent`} // <-- build nested path
            strict
          />
        </Switch>
      </div>
    </div>
  );
};

* Notice I converted to rendering route components via the render prop as opposed to the component prop. When you use anonymous functions to render a component it is created each render cycle, i.e. it will remount the component each time. The render prop does not do this. See render methods for more information.

NavBar

Fix the to prop value to render the link correctly, remove the leading "/" from the path and render the direct link.to value.

Change

to={`/${props.link.to}`}

to

to={props.link.to}

Demo

Edit cannot-code-nested-routes-with-react-router-dom-5-2-0

Drew Reese
  • 165,259
  • 14
  • 153
  • 181