0
votes

Im creating a Dashboard page, where I always want to show a Sidebar Component if the route path is /dashboard. But I also want /dashboard to render another component aswell.

What I am trying to achieve:

  • Route path: /dashboard should render the Sidebar.js + Overview.js components.
  • Route path: /dashboard/account should render Sidebar.js + Account.js components.
  • Route path: /dashboard/favorites should render Sidebar.js + Favorites.js components.
  • And so on...

Can someone point me in the right direction how to achieve this? Cant get my head around it...

See below to get a more feeling of how I want it:

Root route path /dashboard

enter image description here

This is what I tried so far:

              <Route path="/" exact component={Home} />
              <Route path="/podcast/:podId/:podName" component={Podcast} />
              <Route exact path="/categori/:categoryName" component={Category} />
              <AuthRoute path="/login" component={Login} />
              <AuthRoute path="/signup" component={Signup} />
            </Switch>
            <Route
              path="/dashboard"
              render={({ match: { url } }) => (
                <>
                  <Route path={`${url}/`} component={Sidebar} />
                  <Route path={`${url}/`} component={Overview} />
                  <Route path={`${url}/favorites`} component={Favorites} />
                </>
              )}
            />```

1

1 Answers

-1
votes

You should go for composition. Create page components that bring the components together and add the pages to the router.

for e.g. FavoritePage.js will be

<div>
  <Sidebar />
  <Favorites>
</div>

Likewise for the other pages

Then in Router you will have

<Route path={`${url}/`} component={OverviewPage} />
<Route path={`${url}/favorites`} component={FavoritesPage} />

Alternatively if you want the sidebar to be static. Refer https://reacttraining.com/react-router/web/guides/quick-start

   <Router>
      <div>
        <Sidebar />
        {/* A <Switch> looks through its children <Route>s and
            renders the first one that matches the current URL. */}
        <Switch>
          <Route path="/overview">
            <Overview />
          </Route>
          <Route path="/overview">
            <Favorites />
          </Route>
          <Route path="/">
            <Overview />
          </Route>
        </Switch>
      </div>
    </Router>