Home > Enterprise >  React Router v5: Route defined in child component not working
React Router v5: Route defined in child component not working

Time:04-20

My application is using react-router-dom v5.3 and I'm having trouble routing from the root url of my application to a child component (called the "See All" Page) while also passing props down. Currently, my code just renders an empty page whenever I navigate to the child component.

RootRouter.js:

export default function RootRouter() {
  return (
    <BrowserRouter>
         <Switch>
           <Route
             path="/"
             exact
             render={() => <HomeView />}
           />
         </Switch>
    </BrowserRouter>
  );
}

Homeview.js:

function HomeView() {
    const seeAllViewTitle = "some_title_here"
    return (
        <div>
          <div>Some content here!</div>
          <Link to={`/seeall/${seeAllViewTitle}`}}>
             <Button/>
          </Link>
          <Route path={`/seeall/${seeAllViewTitle}`}>
            <SeeAllView
              groupTitle={""}
              pageData={[]}
              eventHandler={some_function_here}
            />
          </Route>
        </div>
      );
}

If I were to put the Route that is currently in homeview.js inside of Rootrouter.js, the component shows up, but I can't pass any props into it from there.

CodePudding user response:

Issue

The HomeView component is rendered only when the path is exactly "/". When the link is clicked and navigates to "/seeall/some_title_here " the path no longer exactly matches and the HomeView component unmounts.

Solution

Remove the exact prop from the root route so nested/sub routes can also be matched and rendered.

export default function RootRouter() {
  return (
    <BrowserRouter>
      <Switch>
        <Route path="/" component={HomeView} />
      </Switch>
    </BrowserRouter>
  );
}

If you did not intend for these components to be rendered at the same time then move the nested route out to the RootRouter component.

export default function RootRouter() {
  return (
    <BrowserRouter>
      <Switch>
        <Route path="/seeall/:title">
          <SeeAllView
            groupTitle={""}
            pageData={[]}
            eventHandler={some_function_here}
          />
        </Route>
        <Route path="/" component={HomeView} />
      </Switch>
    </BrowserRouter>
  );
}

...

function HomeView() {
  const seeAllViewTitle = "some_title_here"
  return (
    <div>
      <div>Some content here!</div>
      <Link to={`/seeall/${seeAllViewTitle}`}}>
        <Button/>
      </Link>
    </div>
  );
}

CodePudding user response:

Are you remembering to receive props in the function declaration for HomeView? usually, you'll need to explicitly define that you are receiving props, either with a props variable or by defining specific prop names in an object syntax

  • Related