šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Using the _app.js file in Nextjs to add common template parts

Whenever you have a component that needs to be present on all your pages the _app.js file may be of help.

Let's say we have the following project structure:

/components
    header.js
    footer.js
/pages
    about.js
    contact.js
    index.js

We need the header and footer components for all three pages: about, contact, and index. A suboptimal solution will be to manually import these components into all the pages:

import {Header} from 'components/header'
import {Footer} from 'components/footer'

export default ()=> {
    return(<div>
        <Header />
        <Footer />
    </div>)
}

In order to avoid repeating all the imports, we can use the _app page. The _app.js is a special page controlling the template of your html pages. It is placed in the root of the pages folder. By default, it starts with the following content:

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />
}
export default MyApp

We can now add the components imports in just this _app.js template file and we will have them included in all of our pages:

import {Header} from 'components/header'
import {Footer} from 'components/footer'
function MyApp({ Component, pageProps }) {
    return (<div>
        <Header />
        <Component {...pageProps} />
        <Footer />
    </div>)
}
export default MyApp

And we can use it also for more things like error handling with componentDidCatch, CSS imports, or state management.

As with the absolute imports, you will need to restart the server the first time you add a _app.js file to your project.

Keep in mind that _app.js is focused on the body template or your NextJs pages. We also have the _document.js page where you have full control of the whole page structure.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

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