1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-02 22:58:01 +00:00

Add Push A Route With A URL Object as a Next.js til

This commit is contained in:
jbranchaud
2021-09-30 12:59:31 -05:00
parent 89c0c33161
commit 2607d4e347
2 changed files with 31 additions and 1 deletions

View File

@@ -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).
_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)
- [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)
- [Ship Public Assets With A Next.js App](nextjs/ship-public-assets-with-a-nextjs-app.md)

View 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.