#Pages router component structure

1 messages · Page 1 of 1 (latest)

spark perch
#

How do I put the components consumed by pages inside the page route?

I believe in app router you can do this

Build optimization failed: found pages without a React Component as default export in
pages/contact/hooks/use-persisted-form
pages/contact/components/contact-form

but I get an error in my vercel build. I don't want to make these components global and contain them to the route

trail lilyBOT
#

Hi @spark perch. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the information provided in the knowledge sources, I can answer your question about the Pages Router component structure and the error you're encountering.

In the Pages Router, you cannot directly place components inside the page route folder as you described. The structure you're trying to use is more aligned with the App Router's approach to colocation.

For the Pages Router, the recommended approach is to keep your components separate from the pages. Typically, you would have a components folder at the root level of your project, outside of the pages directory.

The error you're seeing:

Build optimization failed: found pages without a React Component as default export in 
pages/contact/hooks/use-persisted-form
pages/contact/components/contact-form

This error occurs because the Pages Router expects each file directly under the pages directory (and its subdirectories) to export a default React component that represents a route Pages Router Documentation (https://nextjs.org/docs/pages/building-your-application/routing). Files like hooks or component files are not meant to be placed directly in the pages directory.

To resolve this issue and keep your components scoped to a specific route, you have a couple of options:

  1. Move your components and hooks outside of the pages directory, but maintain a similar folder structure. For example:

    components/
      contact/
        contact-form.js
    hooks/
      contact/
        use-persisted-form.js
    pages/
      contact.js
    
  2. If you're using Next.js 13 or later, consider migrating to the App Router, which supports the colocation of components and other files within route folders App Router Documentation (https://nextjs.org/docs/app/building-your-application/routing#colocation).

#

Remember, in the Pages Router, only files that export a default React component should be placed in the pages directory. Other files like utilities, hooks, or components should be kept outside of pages to avoid build errors.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: