Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

Components vs pages in NextJs

We usually have a ton of info on a real page. We need different components to present and organize this information.

For example, let's say we have a contact.js page with the following content.

export default () => {
    return(<div>
        <h1>Contact page</h1>
        <p>Do not contact us ever!</p>
    </div>
}

We want to add to this page a contact from. In order to separate our code, we will put this form in a contact-form.js.

But where shall we put this contact-form.js? We can’t store that form in our /pages directory, because this will generate a NodeJs page route.

For these cases, we have the shared components folders. You can name a component folder whatever you like, but place it under the root of your NextJs project. So our project will look now like this:

/components
    contact-form.js
/pages
    index.js
    contact.js

With this in place we can now use the components in our NextJs pages:

import {ContactForm} from “../components/contact-form”
export default () => {
    return(<div>
        <h1>Contact page</h1>
        <p>Now you can contact us here:</p>
        <ContactForm />
    </div>
}

If you want to avoid having relative imports like ../components/contact-form we can set up our project to use absolute imports in NextJs.

Keep in mind that for the components that are common to ALL the pages a better alternative will be to import and use them in the pages/_app.js file.

Home Screencasts Best of Newsletter Search X