Home > Back-end >  How does Next.js know to show a component in a layout?
How does Next.js know to show a component in a layout?

Time:01-11

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:

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?

CodePudding user response:

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.

CodePudding user response:

the secret here is in the Page folder it's a special folder because every file in this folder returns a component that will be represented by /its_file_name

that's why you got index.js as the main page because it is represented by /

  • Related