8

I have 3 pages in my React App along with the following routes:

  1. Login (/)
  2. Dashboard (/dashboard)
  3. Projects (/projects)

I would like the Dashboard and Project pages to have a header, but the Login page should not have any header.

Currently the routes look like this:

<Router>
    <Route path="/" component={Login}>
    <Route path="/dashboard" component={Dashboard} />
    <Route path="/projects" component={Projects} />
</Router>

I have created a component called Shell which provides just the header. How do I setup my router so that Shell is parent component for Dashboard and Projects but not the Login page?

Edit 1

I am wondering if it is possible to use a pathless parent like this to render the Shell around the child components:

<Router>
    <Route path="/" component={Login}>
    <Route component={Shell}>
        <Route path="/dashboard" component={Dashboard} />
        <Route path="/projects" component={Projects} />
    </Route>
</Router>

Edit 2

Just tried the change above and it works! Reading the docs, path is not a required prop. So in the code above <Route component={Shell}> is perfectly legit.

Naresh
  • 23,937
  • 33
  • 132
  • 204
  • Your route setup is correct for what you want to do. You just have to render the header in Dashboard and Project. – xiaofan2406 Jan 10 '17 at 00:04
  • 1
    Yeah, but I was wondering if there is any way to use the nested routes feature so that the parent component can render the header and the child components should not have to worry about it. – Naresh Jan 10 '17 at 00:08

2 Answers2

11

What you have in Edit 1 is correct.

<Router>
  <Route component={Login}>
  <Route component={Shell}>
    <Route path="/dashboard" component={Dashboard} />
    <Route path="/projects" component={Projects} />
  </Route>
</Router>

And in your <Shell> component, you can do:

import Header from './Header';

...

render() {
  return (
    <div id="shell">
      <Header />
      {this.props.children}
    </div>
  );
}
...
Calvin
  • 1,305
  • 8
  • 17
0

EDIT 1

I tried this solution with little variation but the two components were merging. So I added Switch which worked for me. So Switch will help you navigate single page at particaular time.

  1. Here first page is Login Page.
  2. Second page is Dashboard. If you want to logout from Dashboard then with the help of switch you can easily navigate to Login page.
<Router>
<Switch>

    <Route path="/" component={Login}>
    <Route path="/shell" component={Shell}>
        <Route path="/dashboard" component={Dashboard} />
        <Route path="/projects" component={Projects} />
    </Route>

<Switch>

</Router>
ZebraCoder
  • 1,480
  • 1
  • 5
  • 12