1

I am using ReactJS and I have a login screen. Only after you login should the user should be shown the header. Right now, the header is appearing on the login screen, which I don't want. How do I get rid of it?

I've tried wrapping the Login path in its own Router, but that doesn't help. The header still renders. The code below is in index.js. That's where all my routing is done and calling other components.

const routing = (
  <div>
    <Router>
      <Switch>
        <Route path="/" exact component={Login} />
      </Switch>
    </Router>
    <Router>
      <Header>
        <Switch>
          <Route path="/landingpage/videos" exact component={Videos} />
        </Switch>
        <Switch>
          <Route path="/landingpage/contact-us" exact component={Contact} />
        </Switch>
        <Switch>
          <Route path="/landingpage/stats/" exact component={Stats} />
        </Switch>
      </Header>
    </Router>
  </div>
);

ReactDOM.render(routing, document.getElementById("root"));
McFloofenbork
  • 983
  • 1
  • 9
  • 21
  • 2
    Why did you use `
    ` in routing? Please use it in other components: `Videos`, `Contact`...
    – Diamond Jun 04 '19 at 14:21
  • ```Header``` is a shared component that all the other pages will have. Why would I re-render it on every page? It would make more sense to render ```Header``` once and then render the actual ```Videos```, ```Contact``` page components. – McFloofenbork Jun 04 '19 at 14:43
  • When you go to every page with route, the whole page should be rendered. To prevent rerendering `Header`, you should not use route to go to every page or it's not a single-page application. – Diamond Jun 04 '19 at 14:55
  • Sounds like what you're saying is similar to the Answer, that I have misconceptions. Thanks! – McFloofenbork Jun 04 '19 at 14:57
  • 1
    You are welcome. Good Luck! :D – Diamond Jun 04 '19 at 15:09

1 Answers1

2

There are some misconceptions in your code, try with:

const routing = (
    <div>
      <Switch>
          <Route path="/" exact component={Login} />
          <Route path="/landingpage/videos" exact render={(props) => <Header><Videos /></Header>} />
          <Route path="/landingpage/contact-us" exact  render={(props) => <Header><Contact /></Header>} />
          <Route path="/landingpage/stats/" exact  render={(props) => <Header><Stats /></Header>} />        
        </Switch>
    </div>
  );

<Router /> renders all matching routes, while <Switch /> render only first matching route.

Additionally, your scaffolding should be wrapping every single component with a route (there are different patterns to manage that, this is only one)

Mosè Raguzzini
  • 14,237
  • 29
  • 40