I want to have one layout for a set of paths, and another layout for another set of paths. Here is my route.jsx:
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import Main from './components/main';
import Home from './components/home';
import MyWork from './components/work/myWork';
import WorkShow from './components/work/workShow';
const DefaultLayout = ({ children }) => (
<div>
<Main children={children} />
</div>
);
const Work = () => (
<Switch>
<Route exact path="/my-work" component={MyWork} />
<Route path="/my-work/:workName" component={WorkShow} />
</Switch>
);
const routes = (
<DefaultLayout>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/my-work" component={Work} />
</Switch>
</DefaultLayout>
);
export default routes;
How would I add another router with a layout of BlogLayout, for example:
<BlogLayout>
<Switch>
<Route path="/blog" component={Blog} />
</Switch>
</BlogLayout>
Assuming you want the /blog path to be included in the switch, you can use the render function of the <Route> component:
const {
HashRouter,
Route,
Switch,
Link,
Redirect
} = ReactRouterDOM
const DefaultLayout = ({ children }) => (
<div>
<p>Main layout</p>
{children}
</div>
);
const AltLayout = ({ children }) => (
<div>
<p>Alternate layout</p>
{children}
</div>
);
const Home = () => (
<span>Home</span>
);
const Work = () => (
<span>Work</span>
);
const Blog = () => (
<span>Blog</span>
);
ReactDOM.render((
<HashRouter>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/work">Work</Link></li>
<li><Link to="/blog">Blog</Link></li>
</ul>
<p>The rendered route component:{' '}
<Switch>
<Route exact path="/" render={() => <DefaultLayout><Home /></DefaultLayout>} />
<Route path="/work" render={() => <DefaultLayout><Work /></DefaultLayout>} />
<Route path="/blog" render={() => <AltLayout><Blog /></AltLayout>} />
</Switch>
</p>
</div>
</HashRouter>
), document.getElementById('app'))
Note, for the working example on Codepen, I had to use <HashRouter>, but this should work regardless of the router you choose.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With