mirror of
https://github.com/jbranchaud/til
synced 2026-01-05 08:08:02 +00:00
Add Push A Route With A URL Object as a Next.js til
This commit is contained in:
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
|||||||
|
|
||||||
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
|
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
|
||||||
|
|
||||||
_1155 TILs and counting..._
|
_1156 TILs and counting..._
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -500,6 +500,7 @@ _1155 TILs and counting..._
|
|||||||
|
|
||||||
- [Create Files And Directories For Dynamic Routes](nextjs/create-files-and-directories-for-dynamic-routes.md)
|
- [Create Files And Directories For Dynamic Routes](nextjs/create-files-and-directories-for-dynamic-routes.md)
|
||||||
- [Define URL Redirects In The Next Config](nextjs/define-url-redirects-in-the-next-config.md)
|
- [Define URL Redirects In The Next Config](nextjs/define-url-redirects-in-the-next-config.md)
|
||||||
|
- [Push A Route With A URL Object](nextjs/push-a-route-with-a-url-object.md)
|
||||||
- [Remove A Query Param From The URL](nextjs/remove-a-query-param-from-the-url.md)
|
- [Remove A Query Param From The URL](nextjs/remove-a-query-param-from-the-url.md)
|
||||||
- [Ship Public Assets With A Next.js App](nextjs/ship-public-assets-with-a-nextjs-app.md)
|
- [Ship Public Assets With A Next.js App](nextjs/ship-public-assets-with-a-nextjs-app.md)
|
||||||
|
|
||||||
|
|||||||
29
nextjs/push-a-route-with-a-url-object.md
Normal file
29
nextjs/push-a-route-with-a-url-object.md
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
# Push A Route With A URL Object
|
||||||
|
|
||||||
|
There are two ways of using the Next.js router to transition to another route
|
||||||
|
using
|
||||||
|
[`push`](https://nextjs.org/docs/api-reference/next/router#with-url-object).
|
||||||
|
|
||||||
|
The first, and perhaps more common, is by passing it a string.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
router.push('/search?tag=react')
|
||||||
|
```
|
||||||
|
|
||||||
|
This is great for simple routes. When routes require query params, this can
|
||||||
|
lead to error-prone string interpolation. That's where the second way comes in.
|
||||||
|
|
||||||
|
The second is to use a [URL
|
||||||
|
Object](https://nextjs.org/docs/api-reference/next/router#with-url-object)
|
||||||
|
instead of a string.
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
router.push({
|
||||||
|
pathname: '/search',
|
||||||
|
query: { tag: 'react' }
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Here we are working with an object. I find objects a bit easier to work with,
|
||||||
|
than strings, when doing programmatic things. Especially when it comes to
|
||||||
|
adding and removing query params.
|
||||||
Reference in New Issue
Block a user