Nikita  Polevoy
Nikita Polevoy

Reputation: 369

How to set up types for react-router-dom?

In my React typescript project I have this code:

import { useLocation } from 'react-router-dom';

export function App() {
  const location = useLocation();
  const background = location.state && location.state.background;
  ...
}

Typescript complains that "Property 'background' does not exist on type '{}'.ts(2339)" How should I expand Location type and make ts happy?

Upvotes: 2

Views: 475

Answers (1)

Mathias Bradiceanu
Mathias Bradiceanu

Reputation: 362

Since react-router-dom useLocation do not accept a generic props as useLocation<{background: boolean}> anymore, you can apply the same solution that Redux Toolkit does with useDispatch and useSelector and simply extend them to add an interface. Here's an example :

import { useLocation } from "react-router-dom";
import type { Location } from "react-router";

// T is to make a generic type so you can use it wherever you want. Feel free to export in into another common types file.
interface LocationWithState<T> extends Location {
  state: T;
}

interface LocationState {
  background: boolean;
  foo: number;
}

export function App() {
  const location = useLocation() as LocationWithState<LocationState>;
  const background = location.state.background; // works ✅
  const foo = location.state.foo; // works ✅
  const bar = location.state.bar; // error ❌
}

Upvotes: 2

Related Questions