Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How does Next.js know to show a component in a layout?

I’m pretty smart on Angular, but need to build a simple demo in next.js.

For the life of me, I can’t figure out how next.js (or I guess, React…) knows to display a given component in a layout.

For instance, I look at this demo:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

https://github.com/vercel/next.js/tree/canary/examples/layout-component

and I don’t see any connection at all between the structure of the application and the decision to display the "Home" component by default. There doesn’t appear to be any code or anything that makes that decision.

Put another way: If I have an app with three components, how does the app determine which one is the default or home one?

Nor do I understand how a component gets passed into the {children} tag.

My Google-Fu is failing me. Happy to be pointed to a simple example that shows how this is done, but I can’t seem to find one. Either that, or I am totally blind to the obvious.

Bottom Line Question: How is the decision made to display any given component?

>Solution :

NextJS uses file/directory based routing, and has a default entry point.

  • NextJS by default renders pages/index.js. This is effectively your / route
  • _app.tsx can be used to apply some general settings, and to provide advanced layout render functionality
  • In _app.tsx specifically the line const getLayout = Component.getLayout ?? ((page) => page) checks if components that are rendered have a getLayout property. If the component you try to render has the getLayout property, it wraps the component you attempt to render in it. This <Component..> becomes page (see below)
  • Based on above bullet, check this in index.tsx
Index.getLayout = function getLayout(page: React.ReactElement) {
  return (
    <Layout>
      <Sidebar />
      {page}
    </Layout>
  )
}
  • Above snippet defines a layout, meaning, it essentially wraps the component, in the snippet referred to as page with some additional "layout". This is done to make Link transitions (NextJSs built-in router) more efficient. This is where the "layout" for the / (what you call home page) is defined.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading