React Router V5 multiple layouts
If you want to test the project you can go to this or clone the repository
yarn or npm install
with this router structure the re-rendering that is caused when changing routes is avoided
In this demo we have two layouts:
- Admin
- Main
The routes
- /
- /about
- /login
- /admin
- /admin/setting
Example file router
import React from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import Main from '../containers/layouts/Main'
import MainAdmin from '../containers/layouts/MainAdmin'
// views
import About from '../containers/views/Main/About'
import Home from '../containers/views/Main/Home'
import Login from '../containers/views/Main/Login'
// admin Views
import Dashboard from '../containers/views/Admin/Dashboard'
import Setting from '../containers/views/Admin/Setting'
export default () => {
return (
<Router>
<Switch>
<Route path='/login' component={Login} />
<Route path='/admin/:path?' exact>
<MainAdmin>
<Switch>
<Route path='/admin' exact component={Dashboard} />
<Route path='/admin/setting' component={Setting} />
</Switch>
</MainAdmin>
</Route>
<Route>
<Main>
<Switch>
<Route path='/' exact component={Home} />
<Route path='/about' component={About} />
</Switch>
</Main>
</Route>
</Switch>
</Router>
)
}
structure folder routers
└── src
├── components
│ └── Common
│ ├── Header
│ └── Footer
├── containers
│ ├── views
│ ├── Main.jsx
│ └── MainAdmin.jsx
│ └── views
│ └── Admin
│ ├── Dashboard
│ └── Setting
│ └── Main
│ ├── About
│ ├── Home
│ └── Login
├── routes
│ └── index.js
Top comments (8)
Hi, thanks for your great article. but i have a problem with multiple layout for one route prefix. In this situation react loads both layouts. this is my code:
How can i fix that?
IMMO the route should not be /admin/login but rather something like /auth/login or just /login
This is because you don't know yet that the person using the login screen is an admin until they have logged on.
Have you tried to lift up ‘Switch’?
Hi, thanks for the great article. I was wondering if you can explain how to pass parameters to the different layouts? i.e if I wanted to have a dynamic view (or header) display inside a layout based on the child route.
Thank you. So simple
I loved it, thanks!
Thanks a lot! But the structure in your picture have a wrong word! Just below of the containers word, there is views folder and it must changed to layouts. Thanks again.
So simple, so perfect. Genius.