Property does not exist on state - Using React Router Hooks with TypeScript

Viewed 648

I having some problems when using react-router-dom hooks + TypeScript.

Trying to access some state property would give an error saying that it doesn't exist

Refer to:

enter image description here

One of the workarounds that I had to do in order to continue development, was to cast it to any

 const location = useLocation() as any;

How can I pass a valid interface to the useLocation generic in order to access state properties without warnings?

  useDidMount(() => {
    if (location.state?.newTransactions) {
      scroll.scrollToBottom();
    }
  });
1 Answers

useLocation accepts a generic parameter that determines the type of the state property, so:

const location = useLocation<YourStateTypeHere>();

For instance:

interface LocationState {
    newTransactions?: boolean;
}

// ...
const location = useLocation<LocationState>();

// ...
useDidMount(() => {
    if (location.state?.newTransactions) {
        scroll.scrollToBottom();
    }
});

How I got there (since I hadn't used that before), in case it's useful: I know that the TypeScript bindings for most hooks implement at least one generic parameter, so when I saw that React Router's location incorporated programmer-defined state, I figured it probably accepted one. So I opened a project where I'm using React Router and TypeScript, and hovered over a useLocation in the code. Sure enough, the popup showed a generic parameter, which got applied to the state property. Result!

Related