Cody
Cody

Reputation: 919

How to create subpages in NEXT.js

I try to get some subpages like

in nextjs https://nextjs.org/

I was able to create pages like

by putting the pages like

page1.js

in the Pages "Folder" but how do I create subpages like

what I tried was creating subfolders in the Pages folder but this did not work and outputted errors.

Help would be much appreciated

Upvotes: 5

Views: 8194

Answers (3)

focus1691
focus1691

Reputation: 351

Create the tests folder inside pages like @karin-bhandari said. You then create a new folder for each subpage with the class or function inside the folder, so in your case it would be:

./pages/tests/project1/project1.js

./pages/tests/project1/project2.js

If you have dynamic routing for the tests directory, then you could conditionally render a page

const Test = props => {
  const router = useRouter();

  return (
    <Layout>
      {router.query.subdirectory === "edit" ? (
        <EditPage />
      ) : (
        <Test id={router.query.id} data={props.data} />
      )}
    </Layout>
  );
};

Where id is a test identifier and subdirectory is the subdirectory path.

Upvotes: 1

Karin Bhandari
Karin Bhandari

Reputation: 31

Create a tests folder inside the pages folder and nextjs will automatically creates a subroute with the name of folder and the pages you create.

Upvotes: 3

Darryl RN
Darryl RN

Reputation: 8228

You can use server like express.js and use the routing system:

const express = require('express')
const next = require('next')

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare()
  .then(() => {
    const server = express()

    server.get('/test/:page', (req, res) => {
      const page = req.params.page;
      let file = '';
      switch(page) {
         case 'page1':
               file = '/page1';
               break;
         case 'page2':
               file = '/page2';
               break;
         default:
               file = '/page1';
      }
      return app.render(req, res, file, { page })
    })

    server.get('*', (req, res) => {
      return handle(req, res)
    })

    server.listen(port, (err) => {
      if (err) throw err
      console.log(`> Ready on http://localhost:${port}`)
    })
  })

Upvotes: -4

Related Questions