I’m making this as simple of an example as possible, I can include more code later if it needs more info to be resolved
I’m using dynamic routes in nextJS. My app pulls results from twitter based on the keywords entered into the dynamic route via API using twitter-v2
package
I’m trying to use the words in the route using router.pathname
in order to create some attributes on the page, but it uses the filename instead of the words in the url.
NextJS version: Next 9.5.3
Render page path: /pages/[keywords].jsx
Example url:
http://localhost:3000/kpop-heroes
example page function:
import Router from 'next/router'
export default function Keywords() {
const router = useRouter();
const KEYWORDS = router.pathname
.slice(1)
.split('-')
.join(' ');
return (
<div>Twitter reactions to <code>{KEYWORDS}</code></div>
)
};
Renders:
Am I misunderstanding this feature? Is it possible to retrieve the words in the url instead of the filename?
Note: I’ve been using window.location.href
as a workaround, but my understanding is accessing the window object is less than optimal
5
Answers
I was just using the wrong method - the correct method is
router.query
.Consider the following url:
log the object produced by the method:
output:
I must've glossed over it, it's clearly in the docs right here: https://nextjs.org/docs/routing/dynamic-routes
Thought I'd leave this up in case someone else confused about it, too
I think the right way is define the dynamic-routes under a specific
path
(ex. /twitter).Render page path:
Example url:
It is unreasonable to define the dynamic-route at the first level of the url.
To get correct URL for both cases e.g. dynamic (
[slug]
) and fixed path:Use the
asPath
property. It returns the path shown in the browser (including the query).https://nextjs.org/docs/api-reference/next/router#router-object
This worked for me
…
…