nextjs query parameter
To use query parameters in Next.js, you can follow these steps:
- Import the
useRouter
hook from thenext/router
module. - Invoke the
useRouter
hook to get access to the router object. - Use the
router.query
object to access the query parameters.
Here is an example of how to use query parameters in Next.js:
import { useRouter } from 'next/router';
function MyComponent() {
const router = useRouter();
const { query } = router;
// Access the query parameters
const name = query.name;
const age = query.age;
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
</div>
);
}
export default MyComponent;
In this example, we import the useRouter
hook from the next/router
module. We then invoke the useRouter
hook to get access to the router object, which provides information about the current route. The router.query
object contains the query parameters passed in the URL.
We can destructure the query
object to get access to the specific query parameters we need. In this case, we access the name
and age
query parameters. We can then use these parameters in our component as needed.
Note that query parameters are typically passed in the URL after a question mark (?), followed by key-value pairs separated by ampersands (&). For example, if the URL is http://example.com/?name=John&age=25
, the name
query parameter would be "John" and the age
query parameter would be "25".
I hope this explanation helps! Let me know if you have any further questions.