0

i'm trying to use nested routing in react router. But my nesting routig not working. If that's make diffrence i'm using Typescript.

//This is working
<Route exact path={path} component={StudentList}></Route>
//This is not working
<Route path={`${path}/:id`} component={StudentComponent}></Route>

I have a module called StudentModule. In module a have two routes like above when i route to /students/1 nothing render

I created a sample app on CodeSandbox https://codesandbox.io/s/vibrant-pasteur-n1eq7

To see what's wrong, navigate to students in menu then click student. It's needs to render StudentComponent and writes Student works on the screen.

Pls help me what's wrong in my code ?

2 Answers2

0

In component StudentModule, please declare the variable id, I think you have missed it and string literal is understanding the id as general string. And pass the url like

<Route exact path={`${path}/${id}`} component={StudentComponent}></Route>

Find the updated code below:

import React from "react";
import { useEffect } from "react";
import { Route, Switch, useRouteMatch } from "react-router-dom";
import StudentComponent from "./Student";
import StudentList from "./StudentList";

export default function StudentModule() {
  let { path } = useRouteMatch();
let id = 1;
  useEffect(() => {
    console.log(path);
  });
  return (
    <Switch>
      <Route exact path={path} component={StudentList}></Route>
      <Route exact path={`${path}/${id}`} component={StudentComponent}></Route>
    </Switch>
  );
}

try it, hope this will be helpful.

0

At your main router, you declared

  <Route exact path="/students" component={StudentModule} />

Because you set path to be exact from one hand, and not declare path as students*, while navigate to students/1, you aren't entering into the Route which holds the sub-router at all.

Hagai Harari
  • 2,767
  • 3
  • 11
  • 23