How to prevent react router 5 to render DashboardLayout component below specific route?

Viewed 27

I am trying to create a route that works as follows:

 <Route path='/home' exact component={Home}/>
{loggedin &&
<DashboardLayout>
<Route path='/settings' exact component={Settings} />
<Route path='/edit' exact component={AdMaker} />
</DashboardLayout>
}

If I am logged in, the DashboardLayout is rendering which I dont want if the route is /home. What should i do? [Please recommend methods other than switch]

2 Answers

There are many different way to do it, one of them is checking the pathname

let location = useLocation();

let checkIsHome = () => {
    return location.pathname?.includes('home')
}
 
<Route path='/home' exact component={Home}/>
{loggedin && !checkIsHome() &&
  <DashboardLayout>
    <Route path='/settings' exact component={Settings} />
    <Route path='/edit' exact component={AdMaker} />
  </DashboardLayout>
}

Use the useRouteMatch in the parent component to determine if the current route is the "/home" path and render the DashboardLayout wrapper component or a React Fragment wrapper.

Example:

const isHome = useRouteMatch("/home");

const LayoutWrapper = loggedIn && !isHome
  ? DashboardLayout
  : React.Fragment;

return (
  ...
  <LayoutWrapper>
    <Route path='/home' exact component={Home}/>
    <Route path='/settings' exact component={Settings} />
    <Route path='/edit' exact component={AdMaker} />
  </LayoutWrapper>
  ...
);

Edit how-to-prevent-react-router-5-to-render-dashboardlayout-component-below-specific

An alternative is to render a non-"/home" route that renders the LayoutWrapper. For this you can provide an array of paths you want to render with the DashboardLayout.

Example:

const LayoutWrapper = loggedIn ? DashboardLayout : React.Fragment;

return (
  ...
  <Route path="/home" exact component={Home} />
  <Route path={["/settings", "/edit"]}>
    <LayoutWrapper>
      <Route path="/settings" exact component={Settings} />
      <Route path="/edit" exact component={AdMaker} />
    </LayoutWrapper>
  </Route>
  ...
);

Edit how-to-prevent-react-router-5-to-render-dashboardlayout-component-below-specific (forked)

OFC, using the Switch component would simplify this all a bit. It's a bit unclear why you wouldn't want to use it. The reason the Switch component is useful and helps is that it exclusively matches and renders routes and you won't need to pepper the exact prop over each and every one of the routes.

Example:

const LayoutWrapper = loggedIn ? DashboardLayout : React.Fragment;

return (
  ...
  <Switch>
    <Route path="/home" component={Home} />
    <Route>
      <LayoutWrapper>
        <Switch>
          <Route path="/settings" component={Settings} />
          <Route path="/edit" component={AdMaker} />
        </Switch>
      </LayoutWrapper>
    </Route>
  </Switch>
  ...
);

Edit how-to-prevent-react-router-5-to-render-dashboardlayout-component-below-specific (forked)

Related