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:
Install React Router:
If you haven't already installed React Router, you can do so using npm or yarn:
bashnpm install react-router-dom
or
bashyarn add react-router-dom
Import useLocation
:
Import the useLocation
hook from React Router in your component file:
javascriptimport { useLocation } from 'react-router-dom';
Access Current URL:
Use the useLocation
hook in your component to access the current URL and location object:
jsximport 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).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:
jsximport 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.