Categories
React Answers

How to use multiple layouts with React Router v4?

Spread the love

Sometimes, we want to use multiple layouts with React Router v4.

In this article, we’ll look at how to use multiple layouts with React Router v4.

How to use multiple layouts with React Router v4?

To use multiple layouts with React Router v4, we just wrap our layout component around the routes.

For instance, we write

const Pages = () => {
  return (
    <ReactRouter>
      <Switch>
        <Route path="/comingsoon" component={ComingSoon} exact />
        <Route>
          <MainLayout>
            <Switch>
              <Route path="/home" exact>
                <Home />
              </Route>
              <Route path="/login" exact>
                <Login />
              </Route>
              <Route path="/useraccount" exact>
                <UserAccount />
              </Route>
            </Switch>
          </MainLayout>
        </Route>
      </Switch>
    </ReactRouter>
  );
};

to wrap MainLayout around some Route components.

Then the layout in Mainlayout would be applied to the components inside, which includes Home , Login, and UserAccount.

Conclusion

To use multiple layouts with React Router v4, we just wrap our layout component around the routes.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *