How to use the useLocation hook in React Router for accessing the current URL



Image not found!!

In React Router, the useLocation hook provides access to the current URL and location object. You can use this hook to access information about the current URL pathname, search parameters, and state. Here's how to use the useLocation hook in React Router:

  1. Install React Router:

    If you haven't already installed React Router, you can do so using npm or yarn:

    bash
    npm install react-router-dom

    or

    bash
    yarn add react-router-dom
  2. Import useLocation:

    Import the useLocation hook from React Router in your component file:

    javascript
    import { useLocation } from 'react-router-dom';
  3. Access Current URL:

    Use the useLocation hook in your component to access the current URL and location object:

    jsx
    import React from 'react'; import { useLocation } from 'react-router-dom'; const MyComponent = () => { const location = useLocation(); return ( <div> <h1>Current URL: {location.pathname}</h1> <p>Search: {location.search}</p> <p>State: {JSON.stringify(location.state)}</p> </div> ); }; export default MyComponent;
    • location.pathname: Returns the path of the current URL.
    • location.search: Returns the query string of the current URL.
    • location.state: Returns the state object associated with the current location (if any).
  4. Accessing Router Props:

    If you are using useLocation in a component that is rendered within a Route, you can also access the same information through router props (match, location, and history). For example:

    jsx
    import React from 'react'; import { withRouter } from 'react-router-dom'; const MyComponent = ({ location }) => { return ( <div> <h1>Current URL: {location.pathname}</h1> <p>Search: {location.search}</p> <p>State: {JSON.stringify(location.state)}</p> </div> ); }; export default withRouter(MyComponent);

    In this example, location is passed as a prop to the component by withRouter.

With the useLocation hook, you can easily access information about the current URL and location object in your React components, allowing you to build dynamic and flexible routing functionality in your application.