Create url with query params in Next.js

Viewed 14623

I want to create an url from query params in the next way:

 router.push(
      {
        pathname: '/cars',
        query: colors + type + price,

      },
      undefined,
      {
        shallow: true,
      },
  );

const colors = ['red', 'blue', 'yellow']; //the arrays could contain many others values
const type = ['offroad', 'sport'];
const price = 'hight'  //this is a string

I want to achieve, when i will click the button which trigger the router.push, the next: /cars?color=red,yellow,blue&type=offroad,sport&price=hight

4 Answers

you can simply do:

 const router = useRouter();
 router.push(
  {
    pathname: '/cars',
    query: {
      colors,
      type,
      price,
  },
  undefined,
  {
    shallow: true,
  },

);

According to Next/Router type, query is typeof ParsedUrlQuery which equivalent to

interface ParsedUrlQuery extends NodeJS.Dict<string | string[]> { }

That is to say, next/router is able to parse both string and array of strings

If you have a dynamic route and want to be able to use this universally, for example, some link on every page (in the header) you can achieve this by providing all currently available route params and add or replace the additional or existing one.

// ...
const router = useRouter();
// ...

<Link
    href={{
        pathname: router.pathname,
        query: { ...router.query, colors, type, price },
    }}
    passHref
    shallow
    replace
></Link>

If you store your params with repeating keys Next.js will recognize it as an array

router.query = color=red&color=green&color=blue
router.push(router)
router.query -> ["red", "green", "blue"]

If you store your params with the same key they will be stored as a single string:

router.query="color=red,green,blue"
router.push(router)
router.query -> red,green,blue

If you want your param key items to be stored in an array:

const params = []
const colors = ['red', 'blue', 'yellow'].map(color => `color=${color}`).join("&")
const type = ['offroad', 'sport'].map(type => `type=${type}`).join("&")
const price = 'hight'

colors && params.push(colors)
type && params.push(type)
price && params.push(price)

const paramsString = params.join('&')
router.params = paramsString
router.push(router)

// This code would result your query.params to be:
query.params -> {color: ['red', 'green', 'blue'], type: ['offroad', 'sports'], price:'hight'}

If you want your param key items to be stored as a string:

const colors = ['red', 'blue', 'yellow']
const type = ['offroad', 'sport']
const price = 'hight'

router.query.colors = colors.join(',')
router.query.type = type.join(',')
router.query.price = price
router.push(router)

// This code would result your query.params to be:
query.params -> {color: 'red,green,blue', type:'offroad,sports', price:'hight'}
Related