πŸ“• Build AI Agents using LangGraph.js is now out!

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.

πŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js

πŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js


Leave a Reply

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