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;
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.
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>();
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.
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 .
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With