Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null-safe way to use Router in next.js with TypeScript

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?

like image 873
Alex Craft Avatar asked Nov 25 '18 14:11

Alex Craft


People also ask

Can you use TypeScript with NextJs?

Next.js provides an integrated TypeScript experience, including zero-configuration set up and built-in types for Pages, APIs, and more.

Can I use react router in next JS?

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.

How do I get a router query in next JS?

To get the query parameter from the above URL inside the <Items> component, we can use the useRouter() hook in next. js.


1 Answers

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'])
...
like image 193
Divyanshu Maithani Avatar answered Oct 05 '22 07:10

Divyanshu Maithani