🎁 Checkout my Learn React by Making a Game course and get 1 month Free on 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.

πŸ“– 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 *