How to get query params in Next.js?

by maryam_feest , in category: JavaScript , 2 years ago

How to get query params in Next.js?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@maryam_feest use router to get query params in Next.js:


1
2
3
4
5
6
7
8
import {useRouter} from 'next/router'

const Product = () => {
    const router = useRouter()
    const {id} = router.query

    return (<div>{id}</div>)
}


by mallie.metz , 10 months ago

@maryam_feest 

In Next.js, you can get query parameters using the useRouter hook, which is part of the next/router module. Here's an example of how to use it:

  1. Import the useRouter hook from next/router:
1
import { useRouter } from 'next/router'


  1. Call the useRouter hook in your component to get access to the router object:
1
const router = useRouter()


  1. Use the query property of the router object to get the query parameters:
1
const { id } = router.query


In this example, we're getting the value of the id query parameter. If the URL of your page is /post?id=123, the value of id will be '123'.


You can also get multiple query parameters by using destructuring:

1
const { id, category } = router.query


In this case, we're getting both the id and category query parameters. If the URL of your page is /post?id=123&category=tech, the value of id will be '123' and the value of category will be 'tech'.