Search code examples
reactjstypescriptreact-routerreact-router-dom

Type or interface for location.state in react-router


In one component, there is a <Link> (from react-router-dom) passing an object in the state property.

Another component called ReceiverComponent is receiving that object correctly. However, the code belows complains with the message:

Type 'PoorMansUnknown' is not assignable to type 'locationStateProps'. Type 'undefined' is not assignable to type 'locationStateProps'.ts(2322)

type locationStateProps = {
  name: string;
}

function ReceiverComponent() {
  const location = useLocation();
  const myState: locationStateProps = location.state;
  return (
    <div>
      {myState.name}
    </div>
  );
}

I need to provide a type for the state some way without this error. How to proceed?


Solution

  • There is a thread open on Github about this issue.

    I implemented this solution mentioned on the thread and it worked.

    interface Props extends RouteComponentProps<
      { myParamProp?: string }, // props.match.params.myParamProp
      any, // history
      { myStateProp?: string }, // props.location.state.myStateProp
    > {
      myNormalProp: boolean;
    }