react how to get current route in typescript

To get the current route in a React TypeScript project that uses react-router-dom, you can use the useLocation hook that comes with react-router-dom. Here's an example:

index.ts
import { useLocation } from "react-router-dom";
import { useEffect, useState } from "react";

const App = () => {
  const location = useLocation();
  const [currentRoute, setCurrentRoute] = useState("");

  useEffect(() => {
    setCurrentRoute(location.pathname);
  }, [location]);

  return <div>Current Route: {currentRoute}</div>;
};
338 chars
14 lines

In the above example, we import the useLocation hook from react-router-dom. We then use the hook to get the current location, which includes the pathname of the current route. We initialize a state variable called currentRoute with an empty string.

We then use the useEffect hook to set the currentRoute whenever the location object changes. This ensures that currentRoute always reflects the current route.

Finally, we render the currentRoute variable inside a div element, so that we can see the current route in the UI.

gistlibby LogSnag