Using multiple layouts for react-router components

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


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>

enter image description here

Source: https://sergiotapia.me/different-layouts-with-react-router-71c553dbe01d


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.

Tags:

React Router