Skip to content
Advertisement

On login screen layout keeps showing – React & React router

As I mentioned I have MUI Theme Provider with Layout which includes Dashboard, Order screens …

When user hits ‘/’ endpoint it should return Login Screen but Layout keeps showing itself.

-App.js

<ThemeProvider theme={theme}>
<Router>
  <Layout>
  <Switch>
      <Route exact path="/">
        <Login />
      </Route>
      <Route  path="/dashboard">
        <Dashboard />
      </Route>
      <Route path="/orders">
        <Orders />
      </Route>
      <Route path="/users">
        <Users />
      </Route>
      <Route path="/employees">
        <Employee />
      </Route>
    </Switch>
  </Layout>
</Router>
</ThemeProvider>

);

-Layout.js

…AppBar,Sidebar etc

<div style={{width:'100%'}}>
        <div className={classes.toolbar}></div>
       {children}
</div>
   

Answer

As-is, the code is unconditionally rendering a Layout component outside the Switch, so it’s rendered regardless of the currently matched route.

If you want the Layout component to only render on certain routes, conditionally render it with those routes.

Example, render the Login component on exactly the "/" path, everything else into a route rendering the Layout and another Switch.

<ThemeProvider theme={theme}>
  <Router>
    <Switch>
      <Route exact path="/">
        <Login />
      </Route>
      <Route path="/">
        <Layout>
          <Switch>
            <Route  path="/dashboard">
              <Dashboard />
            </Route>
            <Route path="/orders">
              <Orders />
            </Route>
            <Route path="/users">
              <Users />
            </Route>
            <Route path="/employees">
              <Employee />
            </Route>
          </Switch>
        </Layout>
      </Route>
    </Switch>
  </Router>
</ThemeProvider>
Advertisement