1

This is a simplified reproduction of the problem: The child with the nested URL does not render.

My file structure is basically this:

-App
 --Home
 --Pageone
  ---Childone

I can render Home or Pageone from App, then I can render Home or Pageone from Pageone or Home respectively, but I cannot render Childone from its 'parent page' Pageone. I am not quite sure what is done wrong.

The code is shared below, and this sandbox

App.jsx

import { BrowserRouter, Switch, Route } from "react-router-dom";
import Pageone from "./Pageone";
import Home from "./Home";

export default function App() {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/">
          <Home />
        </Route>
        <Route exact path="/pageone">
          <Pageone />
        </Route>
      </Switch>
    </BrowserRouter>
  );
}

Home.jsx

import { Link } from "react-router-dom";

const Home = () => {
  return (
    <div>
      <p>This is HOME!</p>
      <Link to="/pageone">Pageone</Link>
    </div>
  );
};

export default Home;

Pageone.jsx

import { Link, Route, useRouteMatch } from "react-router-dom";
import Childone from "./Childone";

const Pageone = () => {
  const { path, url } = useRouteMatch();
  return (
    <div>
      <Route exact path={path}>
        <PageoneContent url={url} />
      </Route>
      <Route exact path={path + "/childone"}>
        <Childone />
      </Route>
    </div>
  );
};

const PageoneContent = (props) => {
  return (
    <div>
      <p>This is pageone!</p>
      <Link to="/">Go back Home</Link>
      <br />
      <Link to={props.url + "/childone"}>Go to Child One</Link>
    </div>
  );
};

export default Pageone;

Childone.jsx

import { Link } from "react-router-dom";

const Childone = () => {
  return (
    <div>
      <p>This is Child one!</p>
      <Link to="/">Go back Home</Link>
    </div>
  );
};

export default Childone;
Mush-A
  • 435
  • 3
  • 11

1 Answers1

1

As far as I know you need to use another Switch for routes, otherwise react will have no idea how to match that route path.

<div>
  <Route exact path={path}>

Should be:

<Switch>
  <Route exact path={path}>
  • This does not appear to work. The `Childone` component still does not appear to render. – Mush-A Aug 13 '21 at 10:57
  • What I've given you is the answer, if it still isn't working then it's because you have the incorrect path or something. –  Aug 13 '21 at 10:59