next.js advices the following pattern to access to the route params:
const Page = withRouter((props) => (
<p>{props.router.query.title}</p>
))
Now the problem is that in TypeScript the code above would show an error because router
and query
could be undefined. It has to be rewritten either as
props.router!.query!.title
or as
props.router && props.router.query && props.router.query.title
both ways are bad in my opinion. In the first one we just forcing compiler to ignore the error and in other bloat the code with unnecessary noise.
Is there a better way to access the route params?
Next.js provides an integrated TypeScript experience, including zero-configuration set up and built-in types for Pages, APIs, and more.
Next. js ships with its own built-in page-based routing system, whereas the typical SPA relies on client-side routing, typically using a library like react-router.
To get the query parameter from the above URL inside the <Items> component, we can use the useRouter() hook in next. js.
There is a proposal for optional chaining in JavaScript, but seems like it'll take a while before it's finalized.
You're correct on avoiding props.router!.query!.title
to ignore the typecheck errors. You would have to conditionally check for the existing properties as you suggested: props.router && props.router.query && props.router.query.title
I usually create a helper function to accept an object and fetch a nested property from it. Or better you can use an existing library such as lodash get:
import get from 'lodash/get'
...
const title = get(props, ['router', 'query', 'title'])
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With