How to get current route in React

In React, you can use the useLocation hook provided by the react-router-dom library to get information about the current route.

Here’s an example of how to use the useLocation hook to get the current route:

import { useLocation } from 'react-router-dom';

function MyComponent() {
  const location = useLocation();

  return (
    <div>
      <p>Current route: {location.pathname}</p>
      <p>Current search query: {location.search}</p>
      <p>Current hash: {location.hash}</p>
    </div>
  );
}

In this example, we import the useLocation hook from the react-router-dom library and call it within the MyComponent function. The useLocation hook returns an object with information about the current location, including the current route path, search query, and hash. We use this object to display the current route information within the MyComponent function.

By using the useLocation hook, you can easily access information about the current route within any component in your React application.

Leave a Reply

Your email address will not be published. Required fields are marked *