Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React TypeScript: Correct type for useLocation() from react-router-dom

I'm struggling to find the right type for this situation. This is a simplified version of redirecting after login. The following produces a compiler error:

Property 'from' does not exist on type '{} | { from: { pathname: string; }; }'.

Adding as any to the use of location.state fixes the compiler error but it's ugly and the linter complains.

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

const AuthLayer: React.FC = (props) => {
  const location = useLocation();

  const { from } = location.state || { from: { pathname: "/" } };

  return <p></p>;
};

export default AuthLayer;
like image 627
Jim Greer Avatar asked May 07 '20 22:05

Jim Greer


People also ask

What is useLocation react dom router?

useLocation. The useLocation hook returns the location object that represents the current URL. You can think about it like a useState that returns a new location whenever the URL changes.

How do you use useParams in react typescript?

In order to useParams you need to implement a generic for useParams. Building on my example above, I need to type the id . type QuizParams = { id: string; }; // In order to implement that, I'd apply my type to the hook when calling it. const { id } = useParams<QuizParams>();

Which tag can be used in react router?

Route: Route is the conditionally shown component that renders some UI when its path matches the current URL. Link: Link component is used to create links to different routes and implement navigation around the application. It works like HTML anchor tag.

How do I set dom on react router?

To install React Router, all you have to do is run npm install react-router-dom@6 in your project terminal and then wait for the installation to complete. If you are using yarn then use this command: yarn add react-router-dom@6 .


1 Answers

You can create a particular type or interface to describe your location state and then use it when calling a useLocation hook:

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

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

const AuthLayer: React.FC = (props) => {
  const location = useLocation<LocationState>();

  const { from } = location.state || { from: { pathname: "/" } };

  return <p></p>;
};

export default AuthLayer;
like image 65
falinsky Avatar answered Oct 28 '22 23:10

falinsky