React Tapas 5 part 2: Layouts
Coming from any other framework is normal to have something like this:
const App = () => {
return (
<Layout>
<Switch>
<Route exact path="/">
<HomePage />
</Route>
<Route exact path="*">
<NotFoundPage />
</Route>
</Switch>
</Layout>
);
}
This has the advantage of writing the Layout once, and applies to all pages...
... but real life is not so simple. It's common to have different layouts for some pages, or we need to change the title of breadcrums of the layout... So we start to make chapuzas until it works.
Not anymore. All those problems disappear if we include the layout in each page:
const HomePage = () => <Layout title="Home" breadcrumbs={...}>Home</Layout>
const NotFoundPage = () => <Layout title="Not found" breadcrumbs={...}>Ooops</Layout>
Using this method (hard to grasp at the beginning) we have the following advantages:
- It's easy to use custom layouts for different pages
- We don't need to use globals (or any other mechanism) to communicate with layout.
- Layout themselves can have or share different components (for example the sidebar)
- Of course, on the other side, we have to include the Layout for each page, but I think it worths in most cases.
I recommend this folder structure:
src/
components/
layouts/
PublicLayout.tsx
PrivateLayout.tsx
LandingLayout.tsx
Sidebar.tsx
...
Where Sidebar (or any other component) is normally treated as private to layouts.