nyphur
nyphur

Reputation: 2866

Nested routing in next js

I've looked around Stackoverflow and the general consensus seems to be adding to my server file.

Though I'm wondering if this is possible with NextJS's dynamic routing.

I'm trying to achieving a route that looks something like this:

/categories/:id/articles/:id

I've tried doing something like this

- pages
  - categories
    - [id]
      - :id.js
      - articles
        - :id.js

To no avail, so perhaps this wasn't the best approach. Would I be able to achieve something like this without touching the server?

Upvotes: 1

Views: 4846

Answers (1)

subashMahapatra
subashMahapatra

Reputation: 6837

Yes it can be done. You need to create a structure in your pages directory like this.

- pages
  - categories
    - [categoryId]
      - articles
        - [articleId].js

In [articleId].js you will have access to params.categoryId and params.articleId.

If you want to show an article list page for /categories/:categoryId/articles you can achieve that by creating a index.js file in the articles folder. Similarly if you want to show a list of categories you can create an index.js file in categories folder For example,

- pages
  - categories
    - index.js   // to show a list of categories
    - [categoryId]
      - articles
        - index.js // to show list of articles for a specific category
        - [articleId].js

To summarize

  • /categories will show NextPage component in pages/categories/index.js.
  • /categories/:categoryId/articles will show NextPage component in pages/categories/[categoryId]/articles/index.js
  • categories/:categoryId/articles/:articlesId will show the NextPage component in pages/categories/[categoryId]/articles/[articleId].js

Upvotes: 10

Related Questions