乐闻世界logo
搜索文章和话题

How do I add a query param to Router.push in NextJS?

1个答案

1

In Next.js, adding query parameters to Router.push is a straightforward and common operation. The Router.push method enables client-side navigation, including passing query parameters. We can add query parameters in two primary ways:

Method One: String Concatenation

We can directly append query parameters to the URL string. This method is intuitive, particularly when the query parameters are minimal and static.

javascript
import { useRouter } from 'next/router'; const Component = () => { const router = useRouter(); const handleClick = () => { router.push('/about?name=John&age=30'); }; return ( <button onClick={handleClick}>Go to About</button> ); }; export default Component;

In the above example, we added two query parameters name and age to the URL of the /about page.

Method Two: Using the URL Object

When dealing with numerous query parameters or dynamic generation, using the URL object offers greater flexibility and readability. This approach allows us to first construct a URL object and then convert it to a string before passing it to Router.push.

javascript
import { useRouter } from 'next/router'; const Component = () => { const router = useRouter(); const handleClick = () => { const url = new URL(window.location.href); url.pathname = '/about'; url.searchParams.set('name', 'John'); url.searchParams.set('age', '30'); router.push(url.href); }; return ( <button onClick={handleClick}>Go to About</button> ); }; export default Component;

In this example, we used the URL object to build the complete URL, including query parameters. Subsequently, we pass the href property of this URL to the Router.push method. The benefit is that it simplifies managing and modifying URL components, especially when handling multiple parameters or conditionally adding them.

Summary

Both methods have distinct advantages, and you can choose based on specific scenarios and personal preference. String concatenation is appropriate for cases with minimal and straightforward query parameters, while using the URL object is preferable for situations involving multiple or complex query parameters. In practice, understanding and effectively applying both methods can significantly enhance development efficiency and code maintainability.

2024年7月18日 00:57 回复

你的答案