How to add location state to a component with React Router and TypeScript?

Sometimes, we want to add location state to a component with React Router and TypeScript.

In this article, we’ll look at how to add location state to a component with React Router and TypeScript.

How to add location state to a component with React Router and TypeScript?

To add location state to a component with React Router and TypeScript, we can use the useLocation hook in our components.

For instance, we write

import { RouteComponentProps, useLocation } from "react-router-dom";
import React from "react";

interface StateType {
  from: { pathname: string };
}

const Comp = () => {
  const { state } = useLocation<StateType>();

  console.log(state.from);
  //...
};

to create Comp component that calls the useLocation hook with and set the type parameter to StateType.

Then we get the state from the object returned from the hook and use it.

We override the unknown type returned by default by useLocation with the StateType interface.

Conclusion

To add location state to a component with React Router and TypeScript, we can use the useLocation hook in our components.