Search code examples
reactjsnext.jsslugnext-router

Next.js Add slug/params to clean URL


I have a structure with a clean URL in the "pages" folder like this ...

/pages/items/[pageNumber]/index.tsx

And if I use router.push I use it like this to get to that page ...

router.replace("/items/[pageNumber]", "/items/1")

That works great, but now I want to add a query params (for filter) to that URL, how can I do that?

I tried this ...

router.push(`/items/[pageNumber]/`, `/items/1/?${filterParams}`, { shallow: true });

But that doesn't work, and I'm wondering how to do that.


Solution

  • When you use it like this

    router.push(`/items/[pageNumber]/`, `/items/1/?${filterParams}`, { shallow: true });
    

    you are not passing query params to the page, you are only showing them in the address bar, I guess.

    How about something like this:

    router.push({
      pathname '/items/[pageNumber]/',
      query: {
        param1: 'yes',
      },
    }, {
      pathname: '/items/1/',
      query: {
        param1: 'yes',
      },
    });
    

    Don't forget to update query part for your case.