diff --git a/README.md b/README.md index 75a380a..66300fe 100644 --- a/README.md +++ b/README.md @@ -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) diff --git a/nextjs/push-a-route-with-a-url-object.md b/nextjs/push-a-route-with-a-url-object.md new file mode 100644 index 0000000..b9385be --- /dev/null +++ b/nextjs/push-a-route-with-a-url-object.md @@ -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.