Mario
Mario

Reputation: 4998

When matching url nested router not working

I have tried for several hours now but without success to identify the reason why this nested router does not work. In the following example in the main component a series of links are listed, among them /surveys that when matching will show the <Surveys /> component, within this component when the url matches /surveys/:id the <Answers /> component should be shown but it never shows. Could you help me identify the reason for this behavior

import ...

function App() {
  // some logic

  return (
    <div>
      <Router>
        <div>
          <nav>
            <ul>
              <li>
                <Link to="/">Home</Link>
              </li>
              <li>
                <Link to="/employees">Employees</Link>
              </li>
              <li>
                <Link to="/surveys">Surveys</Link>
              </li>
              <li>
                <Link to="/survey-creator">Survey creator</Link>
              </li>
            </ul>
          </nav>
        </div>
        <Switch>
          <Route path="/survey-creator">
            <MySurveyCreator />
          </Route>
          <Route path="/employees">
            <Employees employees={state.employees} />
          </Route>
          <Route path="/surveys" exact={true}>
            <Surveys />
          </Route>
          <Route path="/" exact={true}>
            <Home />
          </Route>
        </Switch>
      </Router>
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));

Surveys

import ...

function SingleSurvey({ id, name }) {
  return (
    <li>
      <Link to={`/surveys/${id}`}>{name}</Link>
    </li>
  );
}

export default function Surveys() {
  // some logic

  return (
    <div>
      <h1>Survey</h1>
      <Switch>
        <ul>
          {surveys.map(survey => (
            <SingleSurvey key={survey.id} {...survey} />
          ))}
        </ul>
        <Route exact={true} path={`/${match.path}/:id`}>
          <Answers />
        </Route>
      </Switch>
    </div>
  );
}

Answers

import React from "react";
import { useParams } from "react-router-dom";

export default function Answers() {
  const { id } = useParams();

  console.log(id);

  return (
    <div>
      <h1>Answer</h1>
      <h2>Current id is: {id}</h2>
    </div>
  );
}

Upvotes: 0

Views: 45

Answers (1)

Taghi Khavari
Taghi Khavari

Reputation: 6582

Your nested route is in Serveys Component, So The Serveys Component has to match the url for the nested route but you put an exact keyword for it that won't match with the /surveys/:id

So in result you won't have a Serveys Component that renders <Answers /> Component.

No Servey No Answer :)

just change this:

<Route path="/surveys" exact={true}>
    <Surveys />
</Route>

to this:

<Route path="/surveys">
    <Surveys />
</Route>

Upvotes: 1

Related Questions