next-routes icon indicating copy to clipboard operation
next-routes copied to clipboard

Nesting pages like default Next.js routing

Open hrahimi270 opened this issue 4 years ago • 2 comments

With default Next.js routing that it's based on the file system, we can create nested pages like this:

pages
├── index.js => /
├── about.js => /about
└── auth
    ├── login.js => /auth/login
    ├── register.js => /auth/register

So, how can I implement this routing with next-routes? This example is working?

const routes = require('next-routes');

module.exports = routes()
    .add({name: 'dashboard', pattern: '/', page: 'index'})
    .add({name: 'login', pattern: '/auth/login', page: 'auth/login'})
    .add({name: 'register', pattern: '/auth/register', page: 'auth/register'})

Note: I've used default Next.js routing, so I don't want change my file system for next-routes.

hrahimi270 avatar Oct 02 '19 09:10 hrahimi270

Try this

import routes from "next-routes"; module.exports = routes() .add("index", "/", "index") // Blog .add("blog") .add('blog.detail', '/blog/:id', 'blog/detail')

taufanfadhilah avatar Oct 10 '19 04:10 taufanfadhilah

A workaround we can do is:

  • duplicate the routes and change the params
  • call it using Next.js link instead
  • The page should be in pages root, like /pages/post.js.

In my example below, pages/post is using 2 dynamically params, so I solve it using 2 routes for the same page.

routes.add('category/[slug]', '/category/:slug');
routes.add('postSlug', '/post/:slug', 'post');
routes.add('postLang', '/post/:lang/:slug', 'post');

Case usage

In my category/[slug].js component I'm calling the route as below:

<Link
  href={{
    pathname: '/post',
    query: {
      slug: postSlug
    }
  }}
  as={`/post/${postSlug}`}
>
  Read more &raquo;
</Link>

But if I need to call the post in other languages, I can use the following route:

<Link
  href={{
    pathname: '/post',
    query: {
      slug: postSlug,
      lang: item.slug,
    }
  }}
  as={`/post/${item.slug}/${postSlug}`}
>
  {item.name}
</Link>

Issues related: #296 #291 Related topic: https://stackoverflow.com/a/59259988/3332734

francisrod01 avatar Dec 10 '19 22:12 francisrod01