0

I am new in react. I want my app to have multiple layouts for different pages with react router. The code below was found in https://gist.github.com/avinmathew/e82fe7e757b20cb337d5219e0ab8dc2c

// Custom route component
const AppRoute = ({ component: Component, layout: Layout, ...rest }) => (
  <Route {...rest} render={props => (
    <Layout>
      <Component {...props} />
    </Layout>
  )} />
)

// Actual routes
<Switch>
  <AppRoute exact path="/foo" layout={MainLayout} component={Foo} />
  <AppRoute exact path="/bar" layout={AltLayout} component={Bar} />
  <AppRoute exact path="/bar2" layout={AltLayout} component={Bar2} />
</Switch>

My question is that will the layout be re-rendered after change of pages using same layout, (e.g. from /bar to /bar2)?

2

2 Answers 2

1

Yes. Since Component is a Layout prop and it changes (between Bar1 and Bar2), it will trigger a new render. React uses virtual DOM to only pass the real changes to real DOM.

Sign up to request clarification or add additional context in comments.

1 Comment

does it means that it makes just a little impact on the performance? comparing to the single layout
1

Yes this will re-render your layout upon navigating. The reason for this, is that the render 'function as a child' AKA 'render prop' (this is a design pattern used within React, that react-router-dom implements) gets called upon navigating to that path.

Also - Switch renders the first child or that matches the location.

Try this:

import { Router, Route } from 'react-router-dom';
import { createMemoryHistory } from 'history';

const history = createMemoryHistory();

<Router history={history}>
  <Route component={MainLayout}>
    <Route exact path="/foo" component={Foo} />
  </Route>
  <Route component={AltLayout}>
    <Route exact path="/bar" component={Bar} />
    <Route exact path="/bar2" component={Bar2} />
  </Route>
</Router>

1 Comment

this code seems not working, all layouts will be rendered

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.