I have an admin dashboard and want that only admins are able to see the pages. So I set a condition into my router. When I am logged in, I am able to open every page, but I get the warning:
No routes matched location “/pagename”
Navbar and Sidebar staying in the same position, so that every page opens in a div named ContentWrapper.
How can I get rid of this warning?
Code:
const admin = useAppSelector((state)=>state.auth.user?.isAdmin);
return (
<Container>
<Router>
<Routes>
<Route path="/" element={<Login/>}/>
</Routes>
{admin &&
<>
<Navbar/>
<Wrapper>
<Sidebar/>
<ContentWrapper>
<Routes>
<Route path="/home" element={<Home/>}/>
<Route path="/sales" element={<Sales/>}/>
<Route path="/analytics" element={<Analytics/>}/>
<Route path="/transactions" element={<Transactions/>}/>
<Route path="/reports" element={<Reports/>}/>
<Route path="/mail" element={<Mail/>}/>
<Route path="/feedback" element={<Feedback/>}/>
<Route path="/messages" element={<Messages/>}/>
<Route path="/manage" element={<Manage/>}/>
<Route path="/user" element={<User/>}/>
<Route path="/products" element={<Products/>}/>
<Route path="/productlistChild" element={<ProductlistChild/>}/>
<Route path="/productlistWomen" element={<ProductlistWomen/>}/>
<Route path="/productlistMen" element={<ProductlisttMen/>}/>
<Route path="/productlistSportschuhe" element={<ProductlistSportschuhe/>}/>
<Route path="/productlistSneaker" element={<ProductlistSneaker/>}/>
<Route path="/cardImages" element={<CardImages/>}/>
<Route path="/sneakerImage" element={<SneakerImage/>}/>
<Route path="/sliderImage" element={<SliderImages/>}/>
<Route path="/newsletterBackground" element={<NewsletterBackground/>}/>
<Route path="/descriptionItems" element={<DescriptionItems/>}/>
</Routes>
</ContentWrapper>
</Wrapper>
</>
}
</Router>
</Container>
);
}
Did something similar recently
You can create a PrivateRoute Component
import { Navigate, Outlet } from 'react-router-dom';
const PrivateRouteAdmin = ({ isLoggedIn, role }) => {
return isLoggedIn && role === 'Admin' ? <Outlet /> : <Navigate to="/login" />;
};
export default PrivateRouteAdmin;
and then you can use it in your App.js like this
<Route element={<PrivateRouteAdmin isLoggedIn={isLoggedIn} role={user?.data?.role} />}>
<Route element={<DashboardWrapper />}>
{PublicRoutesAdmin.map((route, index) => {
return <Route key={index} path={route.path} element={<route.component />} />;
})}
</Route>
</Route>
PublicRoutesAdmin.map has just all the routes in a separate file, nothing fancy.
You can have other public routes pout of the private route component
I would resolve this by creating two groups of routes: Private and Public:
const PublicRoutes = () => (
<Fragment>
<Route path="/public/a"><ComponentA /></Route>
<Route path="/public/b"><ComponentB /></Route>
</Fragment>
)
const PrivateRoutes = () => (
<Fragment>
<Route path="/private/a"><PrivComponentA /></Route>
<Route path="/private/b"><PrivComponentB /></Route>
</Fragment>
)
And then have a RootRouter component which conditionally renders either the public or the private routes based on a condition:
const RootRouter = () => {
return (
<Router>
<Routes>
{admin ?
<Fragment>
<PublicRoutes />
<PrivateRoutes />
</Fragment> :
<PublicRoutes />
}
</Routes>
</Router>
)
}
This way, you are rendering the PublicRoutes AND the PrivateRoutes for the admin, but only the PublicRoutes for non-admin users.
I'm trying to use ProtectedRoute as
I can't see why the code isn't working, I'm not getting any error, but at /account it should display <Profile/> and it's blank, I can see the header and footer, but the whole <Profile/> is missing
before trying to use a PrivateRoute, I could display Profile with any problem.
my ProtectedRoute.js
import React from "react";
import { useSelector } from "react-redux";
import { Navigate, Outlet } from "react-router-dom";
const ProtectedRoute = () => {
const {isAuthenticated} = useSelector((state)=>state.user)
return isAuthenticated ? <Outlet /> : <Navigate to="/login"/>
}
export default ProtectedRoute;
my app.js
function App() {
const {isAuthenticated, user} = useSelector(state=>state.user)
React.useEffect(() => {
WebFont.load({
google:{
families: [ "Droid Sans", "Chilanka"],
},
});
store.dispatch(loadUser())
}, []);
return (
<Router>
<Header/>
{isAuthenticated && <UserOptions user={user} />}
<Routes>
<Route exact path="/" element={<Home/>}/>
<Route exact path="/product/:id" element={<ProductDetails/>}/>
<Route exact path="/products" element={<Products/>}/>
<Route path="/products/:keyword" element={<Products/>}/>
<Route exact path="/search" element={<Search/>}/>
<Route exact path="/account" element={<ProtectedRoute/>}/>
<Route exact path="/account" element={<Profile/>}/>
<Route exact path="/login" element={<LoginSignUp/>}/>
</Routes>
<Footer/>
</Router>
);
}
export default App;
and my Profile
const Profile = () => {
const { user, loading, isAuthenticated} = useSelector((state) => state.user);
const navigate = useNavigate();
useEffect(() => {
if(isAuthenticated === false){
navigate("/login");
}
}, [navigate,isAuthenticated])
return (
<Fragment>
<MetaData title={`${user.name}'s Profile`} />
<div className="profileContainer">
<div>
<h1>My Profile</h1>
<img src={user.avatar?.url} alt={user.name} />
<Link to="/me/update">Edit Profile</Link>
</div>
<div>
<div>
<h4>Full Name</h4>
<p>{user.name}</p>
</div>
<div>
<h4>Email</h4>
<p>{user.email}</p>
</div>
<div>
<h4>Joined On</h4>
<p>{String(user.createdAt).substr(0, 10)}</p>
</div>
<div>
<Link to="/orders">My Orders</Link>
<Link to="/password/update">Change Password</Link>
</div>
</div>
</div>
</Fragment>
);
};
export default Profile;
You are rendering two routes for the same "/account" path. ProtectedRoute is rendered on its own self-closing route, so the second route rendering Profile is unreachable.
<Routes>
<Route exact path="/" element={<Home/>}/>
<Route exact path="/product/:id" element={<ProductDetails/>}/>
<Route exact path="/products" element={<Products/>}/>
<Route path="/products/:keyword" element={<Products/>}/>
<Route exact path="/search" element={<Search/>}/>
<Route exact path="/account" element={<ProtectedRoute/>}/>
<Route exact path="/account" element={<Profile/>}/> // <-- unreachable, oops!
<Route exact path="/login" element={<LoginSignUp/>}/>
</Routes>
Remove the path prop from the layout route rendering the ProtectedRoute and ensure it is actually wrapping other Route components. You may as well also remove the exact prop on all the routes as this prop was removed in RRDv6.
Example:
<Router>
<Header/>
{isAuthenticated && <UserOptions user={user} />}
<Routes>
<Route path="/" element={<Home />} />
<Route path="/product/:id" element={<ProductDetails />} />
<Route path="/products" element={<Products />} />
<Route path="/products/:keyword" element={<Products />} />
<Route path="/search" element={<Search />} />
<Route element={<ProtectedRoute />}>
<Route path="/account" element={<Profile />} /> // <-- wrapped by layout route!
</Route>
<Route path="/login" element={<LoginSignUp />} />
</Routes>
<Footer/>
</Router>
The ProtectedRoute component doesn't appear to wait for the user state to populate before rendering either the Outlet for protected content or the redirect. Apply some conditional rendering to render a loading indicator or similar while the user state is populated.
import React from "react";
import { useSelector } from "react-redux";
import { Navigate, Outlet } from "react-router-dom";
const ProtectedRoute = () => {
const user = useSelector((state) => state.user);
if (!user) return null; // <-- or loading indicator, etc...
return user.isAuthenticated
? <Outlet />
: <Navigate to="/login" replace />;
}
export default ProtectedRoute;
I am trying to setup nesting in the react router. I have the following code:
import React from 'react';
import DefaultSwitch from './components/DefaultSwitch/DefaultSwitch';
import './scss/App.scss';
const App = () => {
return (
<DefaultSwitch />
);
};
export default App;
With DefaultSwitch defined as:
const DefaultSwitch = () => {
return (
<Switch>
<Route exact path='/' component={Landing} />
<Route exact path='/login' component={Login} />
<Route exact path='/logout' component={Logout} />
<Route path="/dashboard" component={Dashboard} />
</Switch>
);
}
Inside the Dashboard I have the following:
const Dashboard = () => {
return (
<div>
<MyNavbar />
<DashboardSwitch />
</div>
);
};
And finally DashboardSwitch as:
const DashboardSwitch = () => {
return (
<Switch>
<Route exact path='/dashboard' component={Home} />
<Route exact path='/dashboard/home' component={Home} />
<Route exact path='/dashboard/bonuses' component={Bonuses} />
</Switch>
);
}
Routing appears to work and the correct components are loaded, however I have noticed that if for example I am at /dashboard and then navigate to /dashboard/bonuses the entire page is reloading including the MyNavbar component. I want the navbar to remain static and only the content below it to reload as I have defined in the Dashboard component.
What am I doing wrong here?
Consider using a layout common to all components or something like this to avoid lose MyNavbar, for example:
const App = () => (
<BrowserRouter>
<Layout>
<Switch>
<Route exact path='/' component={Landing} />
<Route exact path='/login' component={Login} />
<Route exact path='/logout' component={Logout} />
<Route exact path='/dashboard' component={Home} />
<Route exact path='/dashboard/home' component={Home} />
<Route exact path='/dashboard/bonuses' component={Bonuses} />
</Switch>
</Layout>
</BrowserRouter>
)
const Layout = ({ children }) => (
<div>
{children}
<MyNavbar />
</div>
);
I am currently struggling with nesting routes using react router v4.
The closest example was the route config in the
React-Router v4 Documentation.
I want to split my app in 2 different parts.
A frontend and an admin area.
I was thinking about something like this:
<Match pattern="/" component={Frontpage}>
<Match pattern="/home" component={HomePage} />
<Match pattern="/about" component={AboutPage} />
</Match>
<Match pattern="/admin" component={Backend}>
<Match pattern="/home" component={Dashboard} />
<Match pattern="/users" component={UserPage} />
</Match>
<Miss component={NotFoundPage} />
The frontend has a different layout and style than the admin area. So within the frontpage the route home, about and so one should be the child routes.
/home should be rendered into the Frontpage component and /admin/home should be rendered within the Backend component.
I tried some other variations but I always ended in not hitting /home or /admin/home.
Final solution:
This is the final solution I am using right now. This example also has a global error component like a traditional 404 page.
import React, { Component } from 'react';
import { Switch, Route, Redirect, Link } from 'react-router-dom';
const Home = () => <div><h1>Home</h1></div>;
const User = () => <div><h1>User</h1></div>;
const Error = () => <div><h1>Error</h1></div>
const Frontend = props => {
console.log('Frontend');
return (
<div>
<h2>Frontend</h2>
<p><Link to="/">Root</Link></p>
<p><Link to="/user">User</Link></p>
<p><Link to="/admin">Backend</Link></p>
<p><Link to="/the-route-is-swiggity-swoute">Swiggity swooty</Link></p>
<Switch>
<Route exact path='/' component={Home}/>
<Route path='/user' component={User}/>
<Redirect to={{
state: { error: true }
}} />
</Switch>
<footer>Bottom</footer>
</div>
);
}
const Backend = props => {
console.log('Backend');
return (
<div>
<h2>Backend</h2>
<p><Link to="/admin">Root</Link></p>
<p><Link to="/admin/user">User</Link></p>
<p><Link to="/">Frontend</Link></p>
<p><Link to="/admin/the-route-is-swiggity-swoute">Swiggity swooty</Link></p>
<Switch>
<Route exact path='/admin' component={Home}/>
<Route path='/admin/user' component={User}/>
<Redirect to={{
state: { error: true }
}} />
</Switch>
<footer>Bottom</footer>
</div>
);
}
class GlobalErrorSwitch extends Component {
previousLocation = this.props.location
componentWillUpdate(nextProps) {
const { location } = this.props;
if (nextProps.history.action !== 'POP'
&& (!location.state || !location.state.error)) {
this.previousLocation = this.props.location
};
}
render() {
const { location } = this.props;
const isError = !!(
location.state &&
location.state.error &&
this.previousLocation !== location // not initial render
)
return (
<div>
{
isError
? <Route component={Error} />
: <Switch location={isError ? this.previousLocation : location}>
<Route path="/admin" component={Backend} />
<Route path="/" component={Frontend} />
</Switch>}
</div>
)
}
}
class App extends Component {
render() {
return <Route component={GlobalErrorSwitch} />
}
}
export default App;
In react-router-v4 you don't nest <Routes />. Instead, you put them inside another <Component />.
For instance
<Route path='/topics' component={Topics}>
<Route path='/topics/:topicId' component={Topic} />
</Route>
should become
<Route path='/topics' component={Topics} />
with
const Topics = ({ match }) => (
<div>
<h2>Topics</h2>
<Link to={`${match.url}/exampleTopicId`}>
Example topic
</Link>
<Route path={`${match.path}/:topicId`} component={Topic}/>
</div>
)
Here is a basic example straight from the react-router documentation.
react-router v6
Update for 2022 - v6 has nested Route components that Just Work™.
This question is about v4/v5, but the best answer now is just use v6 if you can!
See example code in this blog post. If you can't upgrade just yet, however...
react-router v4 & v5
It's true that in order to nest Routes you need to place them in the child component of the Route.
However if you prefer a more inline syntax rather than breaking your Routes up across components, you can provide a functional component to the render prop of the Route you want to nest under.
<BrowserRouter>
<Route path="/" component={Frontpage} exact />
<Route path="/home" component={HomePage} />
<Route path="/about" component={AboutPage} />
<Route
path="/admin"
render={({ match: { url } }) => (
<>
<Route path={`${url}/`} component={Backend} exact />
<Route path={`${url}/home`} component={Dashboard} />
<Route path={`${url}/users`} component={UserPage} />
</>
)}
/>
</BrowserRouter>
If you're interested in why the render prop should be used, and not the component prop, it's because it stops the inline functional component from being remounted on every render. See the documentation for more detail.
Note the example wraps the nested Routes in a Fragment. Prior to React 16, you can use a container <div> instead.
Just wanted to mention react-router v4 changed radically since this question was posted/answed.
There is no <Match> component any more! <Switch>is to make sure only the first match is rendered. <Redirect> well .. redirects to another route. Use or leave out exact to either in- or exclude a partial match.
See the docs. They are great. https://reacttraining.com/react-router/
Here's an example I hope is useable to answer your question.
<Router>
<div>
<Redirect exact from='/' to='/front'/>
<Route path="/" render={() => {
return (
<div>
<h2>Home menu</h2>
<Link to="/front">front</Link>
<Link to="/back">back</Link>
</div>
);
}} />
<Route path="/front" render={() => {
return (
<div>
<h2>front menu</h2>
<Link to="/front/help">help</Link>
<Link to="/front/about">about</Link>
</div>
);
}} />
<Route exact path="/front/help" render={() => {
return <h2>front help</h2>;
}} />
<Route exact path="/front/about" render={() => {
return <h2>front about</h2>;
}} />
<Route path="/back" render={() => {
return (
<div>
<h2>back menu</h2>
<Link to="/back/help">help</Link>
<Link to="/back/about">about</Link>
</div>
);
}} />
<Route exact path="/back/help" render={() => {
return <h2>back help</h2>;
}} />
<Route exact path="/back/about" render={() => {
return <h2>back about</h2>;
}} />
</div>
</Router>
Hope it helped, let me know. If this example is not answering your question well enough, tell me and I'll see if I can modify it.
I succeeded in defining nested routes by wrapping with Switch and define nested route before than root route.
<BrowserRouter>
<Switch>
<Route path="/staffs/:id/edit" component={StaffEdit} />
<Route path="/staffs/:id" component={StaffShow} />
<Route path="/staffs" component={StaffIndex} />
</Switch>
</BrowserRouter>
Reference: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Switch.md
Using Hooks
The latest update with hooks is to use useRouteMatch.
Main routing component
export default function NestingExample() {
return (
<Router>
<Switch>
<Route path="/topics">
<Topics />
</Route>
</Switch>
</Router>
);
}
Child component
function Topics() {
// The `path` lets us build <Route> paths
// while the `url` lets us build relative links.
let { path, url } = useRouteMatch();
return (
<div>
<h2>Topics</h2>
<h5>
<Link to={`${url}/otherpath`}>/topics/otherpath/</Link>
</h5>
<ul>
<li>
<Link to={`${url}/topic1`}>/topics/topic1/</Link>
</li>
<li>
<Link to={`${url}/topic2`}>/topics/topic2</Link>
</li>
</ul>
// You can then use nested routing inside the child itself
<Switch>
<Route exact path={path}>
<h3>Please select a topic.</h3>
</Route>
<Route path={`${path}/:topicId`}>
<Topic />
</Route>
<Route path={`${path}/otherpath`>
<OtherPath/>
</Route>
</Switch>
</div>
);
}
Some thing like this.
import React from 'react';
import {
BrowserRouter as Router, Route, NavLink, Switch, Link
} from 'react-router-dom';
import '../assets/styles/App.css';
const Home = () =>
<NormalNavLinks>
<h1>HOME</h1>
</NormalNavLinks>;
const About = () =>
<NormalNavLinks>
<h1>About</h1>
</NormalNavLinks>;
const Help = () =>
<NormalNavLinks>
<h1>Help</h1>
</NormalNavLinks>;
const AdminHome = () =>
<AdminNavLinks>
<h1>root</h1>
</AdminNavLinks>;
const AdminAbout = () =>
<AdminNavLinks>
<h1>Admin about</h1>
</AdminNavLinks>;
const AdminHelp = () =>
<AdminNavLinks>
<h1>Admin Help</h1>
</AdminNavLinks>;
const AdminNavLinks = (props) => (
<div>
<h2>Admin Menu</h2>
<NavLink exact to="/admin">Admin Home</NavLink>
<NavLink to="/admin/help">Admin Help</NavLink>
<NavLink to="/admin/about">Admin About</NavLink>
<Link to="/">Home</Link>
{props.children}
</div>
);
const NormalNavLinks = (props) => (
<div>
<h2>Normal Menu</h2>
<NavLink exact to="/">Home</NavLink>
<NavLink to="/help">Help</NavLink>
<NavLink to="/about">About</NavLink>
<Link to="/admin">Admin</Link>
{props.children}
</div>
);
const App = () => (
<Router>
<div>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/help" component={Help}/>
<Route path="/about" component={About}/>
<Route exact path="/admin" component={AdminHome}/>
<Route path="/admin/help" component={AdminHelp}/>
<Route path="/admin/about" component={AdminAbout}/>
</Switch>
</div>
</Router>
);
export default App;
A complete answer for React Router v6 or version 6 just in case needed.
import Dashboard from "./dashboard/Dashboard";
import DashboardDefaultContent from "./dashboard/dashboard-default-content";
import { Route, Routes } from "react-router";
import { useRoutes } from "react-router-dom";
/*Routes is used to be Switch*/
const Router = () => {
return (
<Routes>
<Route path="/" element={<LandingPage />} />
<Route path="games" element={<Games />} />
<Route path="game-details/:id" element={<GameDetails />} />
<Route path="dashboard" element={<Dashboard />}>
<Route path="/" element={<DashboardDefaultContent />} />
<Route path="inbox" element={<Inbox />} />
<Route path="settings-and-privacy" element={<SettingsAndPrivacy />} />
<Route path="*" element={<NotFound />} />
</Route>
<Route path="*" element={<NotFound />} />
</Routes>
);
};
export default Router;
import DashboardSidebarNavigation from "./dashboard-sidebar-navigation";
import { Grid } from "#material-ui/core";
import { Outlet } from "react-router";
const Dashboard = () => {
return (
<Grid
container
direction="row"
justify="flex-start"
alignItems="flex-start"
>
<DashboardSidebarNavigation />
<Outlet />
</Grid>
);
};
export default Dashboard;
Github repo is here. https://github.com/webmasterdevlin/react-router-6-demo
React Router v6
allows to use both nested routes (like in v3) and separate, splitted routes (v4, v5).
Nested Routes
Keep all routes in one place for small/medium size apps:
<Routes>
<Route path="/" element={<Home />} >
<Route path="user" element={<User />} />
<Route path="dash" element={<Dashboard />} />
</Route>
</Routes>
const App = () => {
return (
<BrowserRouter>
<Routes>
// /js is start path of stack snippet
<Route path="/js" element={<Home />} >
<Route path="user" element={<User />} />
<Route path="dash" element={<Dashboard />} />
</Route>
</Routes>
</BrowserRouter>
);
}
const Home = () => {
const location = useLocation()
return (
<div>
<p>URL path: {location.pathname}</p>
<Outlet />
<p>
<Link to="user" style={{paddingRight: "10px"}}>user</Link>
<Link to="dash">dashboard</Link>
</p>
</div>
)
}
const User = () => <div>User profile</div>
const Dashboard = () => <div>Dashboard</div>
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://unpkg.com/react#16.13.1/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom#16.13.1/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/history#5.0.0/umd/history.production.min.js"></script>
<script src="https://unpkg.com/react-router#6.0.0-alpha.5/umd/react-router.production.min.js"></script>
<script src="https://unpkg.com/react-router-dom#6.0.0-alpha.5/umd/react-router-dom.production.min.js"></script>
<script>var { BrowserRouter, Routes, Route, Link, Outlet, useNavigate, useLocation } = window.ReactRouterDOM;</script>
Alternative: Define your routes as plain JavaScript objects via useRoutes.
Separate Routes
You can use separates routes to meet requirements of larger apps like code splitting:
// inside App.jsx:
<Routes>
<Route path="/*" element={<Home />} />
</Routes>
// inside Home.jsx:
<Routes>
<Route path="user" element={<User />} />
<Route path="dash" element={<Dashboard />} />
</Routes>
const App = () => {
return (
<BrowserRouter>
<Routes>
// /js is start path of stack snippet
<Route path="/js/*" element={<Home />} />
</Routes>
</BrowserRouter>
);
}
const Home = () => {
const location = useLocation()
return (
<div>
<p>URL path: {location.pathname}</p>
<Routes>
<Route path="user" element={<User />} />
<Route path="dash" element={<Dashboard />} />
</Routes>
<p>
<Link to="user" style={{paddingRight: "5px"}}>user</Link>
<Link to="dash">dashboard</Link>
</p>
</div>
)
}
const User = () => <div>User profile</div>
const Dashboard = () => <div>Dashboard</div>
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://unpkg.com/react#16.13.1/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom#16.13.1/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/history#5.0.0/umd/history.production.min.js"></script>
<script src="https://unpkg.com/react-router#6.0.0-alpha.5/umd/react-router.production.min.js"></script>
<script src="https://unpkg.com/react-router-dom#6.0.0-alpha.5/umd/react-router-dom.production.min.js"></script>
<script>var { BrowserRouter, Routes, Route, Link, Outlet, useNavigate, useLocation } = window.ReactRouterDOM;</script>
You can try something like
Routes.js
import React, { Component } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom';
import FrontPage from './FrontPage';
import Dashboard from './Dashboard';
import AboutPage from './AboutPage';
import Backend from './Backend';
import Homepage from './Homepage';
import UserPage from './UserPage';
class Routes extends Component {
render() {
return (
<div>
<Route exact path="/" component={FrontPage} />
<Route exact path="/home" component={Homepage} />
<Route exact path="/about" component={AboutPage} />
<Route exact path="/admin" component={Backend} />
<Route exact path="/admin/home" component={Dashboard} />
<Route exact path="/users" component={UserPage} />
</div>
)
}
}
export default Routes
App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route } from 'react-router-dom'
import Routes from './Routes';
class App extends Component {
render() {
return (
<div className="App">
<Router>
<Routes/>
</Router>
</div>
);
}
}
export default App;
I think you can achieve the same from here also.
A complete answer for React Router v5.
const Router = () => {
return (
<Switch>
<Route path={"/"} component={LandingPage} exact />
<Route path={"/games"} component={Games} />
<Route path={"/game-details/:id"} component={GameDetails} />
<Route
path={"/dashboard"}
render={({ match: { path } }) => (
<Dashboard>
<Switch>
<Route
exact
path={path + "/"}
component={DashboardDefaultContent}
/>
<Route path={`${path}/inbox`} component={Inbox} />
<Route
path={`${path}/settings-and-privacy`}
component={SettingsAndPrivacy}
/>
<Redirect exact from={path + "/*"} to={path} />
</Switch>
</Dashboard>
)}
/>
<Route path="/not-found" component={NotFound} />
<Redirect exact from={"*"} to={"/not-found"} />
</Switch>
);
};
export default Router;
const Dashboard = ({ children }) => {
return (
<Grid
container
direction="row"
justify="flex-start"
alignItems="flex-start"
>
<DashboardSidebarNavigation />
{children}
</Grid>
);
};
export default Dashboard;
Github repo is here. https://github.com/webmasterdevlin/react-router-5-demo
I prefer to use react function. This solution is short and more readable
const MainAppRoutes = () => (
<Switch>
<Route exact path='/' component={HomePage} />
{AdminRoute()}
{SampleRoute("/sample_admin")}
</Switch>
);
/*first implementation: without params*/
const AdminRoute = () => ([
<Route path='/admin/home' component={AdminHome} />,
<Route path='/admin/about' component={AdminAbout} />
]);
/*second implementation: with params*/
const SampleRoute = (main) => ([
<Route path={`${main}`} component={MainPage} />,
<Route path={`${main}/:id`} component={MainPage} />
]);
**This code worked for me with v6**
index.js
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<Routes>
<Route path="/" element={<App />}>
<Route path="login" element={<Login />} />
<Route path="home" element={<Home />} />
</Route>
</Routes>
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
App.js:
function App(props) {
useEffect(() => {
console.log('reloaded');
// Checking, if Parent component re-rendering or not *it should not be, in the sense of performance*, this code doesn't re-render parent component while loading children
});
return (
<div className="App">
<Link to="login">Login</Link>
<Link to="home">Home</Link>
<Outlet /> // This line is important, otherwise we will be shown with empty component
</div>
);
}
login.js:
const Login = () => {
return (
<div>
Login Component
</div>
)
};
home.js:
const Home= () => {
return (
<div>
Home Component
</div>
)
};
interface IDefaultLayoutProps {
children: React.ReactNode
}
const DefaultLayout: React.SFC<IDefaultLayoutProps> = ({children}) => {
return (
<div className="DefaultLayout">
{children}
</div>
);
}
const LayoutRoute: React.SFC<IDefaultLayoutRouteProps & RouteProps> = ({component: Component, layout: Layout, ...rest}) => {
const handleRender = (matchProps: RouteComponentProps<{}, StaticContext>) => (
<Layout>
<Component {...matchProps} />
</Layout>
);
return (
<Route {...rest} render={handleRender}/>
);
}
const ScreenRouter = () => (
<BrowserRouter>
<div>
<Link to="/">Home</Link>
<Link to="/counter">Counter</Link>
<Switch>
<LayoutRoute path="/" exact={true} layout={DefaultLayout} component={HomeScreen} />
<LayoutRoute path="/counter" layout={DashboardLayout} component={CounterScreen} />
</Switch>
</div>
</BrowserRouter>
);
If I have the following:
<Route path="/" component={Containers.App}>
{ /* Routes that use layout 1 */ }
<IndexRoute component={Containers.Home}/>
<Route path="about" component={Containers.About}/>
<Route path="faq" component={Containers.Faq}/>
<Route path="etc" component={Containers.Etc}/>
{ /* Routes that use layout 2 */ }
<Route path="products" component={Containers.Products}/>
<Route path="gallery" component={Containers.Gallery}/>
</Route>
How can I make it so that the two sets of routes each use a different layout.
If I only had a single layout then I would put it in App, but in this case where do I define the layout?
To make it even more complicated some of the layout components (eg top nav) are shared between both layout types.
You can use routes without a path to define containers that are not defined by the url:
<Route path="/" component={Containers.App}>
{ /* Routes that use layout 1 */ }
<Route component={Containers.Layout1}>
<IndexRoute component={Containers.Home}/>
<Route path="about" component={Containers.About}/>
<Route path="faq" component={Containers.Faq}/>
<Route path="etc" component={Containers.Etc}/>
</Route>
<Route component={Containers.Layout2}>
{ /* Routes that use layout 2 */ }
<Route path="products" component={Containers.Products}/>
<Route path="gallery" component={Containers.Gallery}/>
</Route>
</Route>
The layout components can then import additional components such as the top nav
Route's path property has accepted an array of strings for a while now. See https://github.com/ReactTraining/react-router/pull/5889/commits/4b79b968389a5bda6141ac83c7118fba9c25ff05
Simplified to match the question routes, but I have working multiple layouts essentially like this (using react-router 5):
<App>
<Switch>
<Route path={["/products", "/gallery"]}>
<LayoutTwo>
<Switch>
<Route path="/products" component={Products} />
<Route path="/gallery" component={Gallery} />
</Switch>
</LayoutTwo>
</Route>
{/* Layout 1 is last because it is used for the root "/" and will be greedy */}
<Route path={["/about", "/faq", "/etc", "/"]}>
<LayoutOne>
<Switch>
<IndexRoute component={Home} />
<Route path="/about" component={About} />
<Route path="/faq" component={Faq} />
<Route path="/etc" component={Etc} />
</Switch>
</LayoutOne>
</Route>
</Switch>
</App>
This solution prevents re-mounting the layouts on route changes, which can break transitions, etc.
Here's a great way to use multiple layouts with different React components.
In your router you can use:
<Router history={browserHistory}>
<Route component={MainLayout}>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
</Route>
<Route component={EmptyLayout}>
<Route path="/sign-in" component={SignIn} />
</Route>
<Route path="*" component={NotFound}/>
</Router>
Source: https://sergiotapia.me/different-layouts-with-react-router-71c553dbe01d
Pintouch, I was able to get this working with the following example:
Layout1:
import React from 'react'
const Layout1 = (props) => (
<div>
<h1>Layout 1</h1>
{props.children}
</div>
)
export default Layout1
Layout2:
import React from 'react'
const Layout2 = (props) => (
<div>
<h1>Layout 2</h1>
{props.children}
</div>
)
export default Layout2
Layout Container:
import React from 'react'
const LayoutContainer = (props) => (
<div>
{props.children}
</div>
)
export default LayoutContainer
Routes:
import React from 'react';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';
import LayoutContainer from './LayoutContainer'
import Layout1 from './Layout1'
import Layout2 from './Layout2'
import ContactManagerView from './ContactManagerView'
import CallerIdView from './CallerIdView'
import NotFound from './NotFound'
<Router history={hashHistory}>
<Route path="/" component={LayoutContainer}>
<Route component={Layout1}>
<IndexRoute component={DashboardView}/>
<Route path='Contacts' component={ContactManagerView}/>
</Route>
<Route component={Layout2}>
<Route path='CallerId' component={CallerIdView}/>
</Route>
<Route component={Layout}>
<Route path='*' component={NotFound}/>
</Route>
</Route>
</Router>
This is how it's done in React Router v6:
<Route path="/" element={<App />}>
{/* Routes that use layout 1 */}
<Route element={<BlueLayout />}>
<Route index element={<Home />} />
<Route path="about" element={<About />} />
<Route path="faq" element={<Faq />} />
<Route path="etc" element={<Etc />} />
</Route>
{/* Routes that use layout 2 */}
<Route element={<RedLayout />}>
<Route path="products" element={<Products />} />
<Route path="gallery" element={<Gallery />} />
</Route>
</Route>
I've created a complete example in StackBlitz here.
You could create a function RouteWithLayout that renders the <Route> wrapped within the layout:
const RouteWithLayout = ({ component: Component, layout: Layout, ...rest }) => (
<Route {...rest} render={props => (
<Layout>
<Component {...props} />
</Layout>
)} />
)
const MainLayout = props => (
<div>
<h1>Main</h1>
{props.children}
</div>
)
const AltLayout = props => (
<div>
<h1>Alt</h1>
{props.children}
</div>
)
const Foo = () => (
<p>Foo</p>
)
const Bar = () => (
<p>Bar</p>
)
const App = () => (
<div>
<Switch>
<RouteWithLayout exact path="/foo" layout={MainLayout} component={Foo} />
<RouteWithLayout exact path="/bar" layout={AltLayout} component={Bar} />
</Switch>
</div>
)
I came across this question and found a solution that I want to share.
With react router v4 we could render the routes directly in your layout. Which is more readable and easy to maintain.
Layout
export class MainLayout extends React.PureComponent {
render() {
return (
<div>
<Header />
{this.props.children}
<Footer />
</div>
);
}
}
Mainlayout.propTypes = {
children: PropTypes.node.isRequired,
}
Router
export default function App() {
return (
<Switch>
<MainLayout>
<Switch>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
</Switch>
</MainLayout>
<OtherLayout>
.... other paths
</OtherLayout>
</Switch>
);
}