How To Add URL Parameters Using NextJS

React

Next.js

13/03/2023


NextJS makes it easy to add URL parameters with next/router.

JAVASCRIPT
const router = useRouter()

The router object, returned by the useRouter hook, accepts a URL of type UrlObject, which is a NodeJS module. In particular, the query property accepts an object which is transformed into a URL query string.

JAVASCRIPT
// `.push` is used as an example. This work with `.replace` and `.prefetch` as well.
router.replace({
// Path of the URL
pathname: "/menu",
query: {
fruit: "banana",
softDrink: "fanta",
},
})

The example above would yield the following result: /menu?fruit=banana&softDrink=fanta.


WRITTEN BY

Code and stuff