Like other React hooks, React Router DOM provides a hook for handling the URL data in the component. This hook is known as useLocation hook. The useLocation hook returns the location object from the current URL. The URL may contain different segments, parameters, query strings, etc. Therefore, by using this location object, it allows us to get these values. We will see all these by implementing them in this post. We have already seen the overview of using React Router DOM V6 in React JS. In this post, we will focus on the React useLocation hook only.
Prerequisites
I assume, you are already familiar with the basics of React. Also, having a good understanding of React Router DOM. This post will be totally dependent on these.
If you don’t have a React app setup, then you can create it. Else, you can move ahead with the existing React App.
Redirect to Component with Props Using useNavigate Hook
Create React App
You can create a new app in React Js using the below command.
npx create-react-app react-router-app
After creating the app, open it in your favourite editor and run it.
npm start
The application will be started in the browser as shown below.
In the next step, you will require to install the React Router DOM library in your app.
How to Create Todo App in React JS Using Redux
Install React Router DOM
We are going to use the useLocation hook in this post. So, this hook is provided by the React Router DOM library. So, install it using the below command.
npm i react-router-dom
Once, this library is installed, we need a few components to implement the useLocation hook.
Create Components in React
We will create a few components in our app. So, initially, inside the src folder, create a folder named components. Now, inside the components folder, create the below components.
- Home.jsx
- About.jsx
After creating the components, let’s add the snippets.
import React from "react";
import { useNavigate } from "react-router-dom";
export const Home = () => {
const navigate = useNavigate();
// redirecting to about component
const redirectToAbout = () => {
navigate("/about", {
state: {
name: 'Programming Fields',
message: 'Message from home component',
},
});
};
return (
<div className="container text-center py-5">
<h3> Home component </h3>
<button
type="button"
className="btn btn-primary"
onClick={redirectToAbout}
>
Redirect to About
</button>
</div>
);
};
In this component, I have used useNavigate hook to redirect to About component with some props.
Now, in the About component, we will capture this props using the useLocation hook.
So, let’s understand in the below snippet.
import React from "react";
import { useLocation, useNavigate } from "react-router-dom";
export const About = () => {
const navigate = useNavigate();
const location = useLocation();
console.log('location', location)
const redirectToHome = () => {
navigate("/");
};
return (
<div className="container text-center py-5">
<h3> About Us Component </h3>
<h5> {location.state.name} </h5>
<p> {location.state.message} </p>
<button
type="button"
className="btn btn-primary"
onClick={redirectToHome}
>
Redirect to Home
</button>
</div>
);
};
Here, in the About component, I have imported the React useLocation hook. Then created an object of this hook.
Let’s see the result first. I have logged the location object in the console.
In the above result, if you will notice the console, we have the location object. It returns the following –
- hash – It is a result of the hash fragment (#) which will come through the URL.
- pathname – This will return the current URL (pathname).
- search – You can get the query string if any in the URL.
- state – The state object is used to handle props with navigate object.
Form Handling in React JS Using React Hook Form Library
Handle Query String in React Using useLocation Hook
Let’s try to pass a query string from the Home component to About. So, in the navigate function, we can pass the query parameter.
const redirectToAbout = () => {
navigate("/about?name=react", {
state: {
name: 'Programming Fields',
message: 'Message from home component',
},
});
};
Now, try to navigate to the About component and see the result.
In the result, you will see the location object having a search value. In the search, we have the ?name=react
.
Here, we can extract the search (query string) value and use it for further implementation.
import React, { useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
export const About = () => {
const navigate = useNavigate();
const location = useLocation();
useEffect(() => {
if (location.search) {
// perform any action
console.log('search', location.search)
}
}, [location]);
const redirectToHome = () => {
navigate("/");
};
return (
<div className="container text-center py-5">
<h3> About Us Component </h3>
<h5> {location.state.name} </h5>
<p> {location.state.message} </p>
<button
type="button"
className="btn btn-primary"
onClick={redirectToHome}
>
Redirect to Home
</button>
</div>
);
};
For capturing the query string value, I have used React useEffect hook. So, if the location object has some search value then it will be invoked automatically. Based on the search value, you can perform any action related to that value.
Handle Large Query String
In the above snippet, we have seen we had a single-word query string. Now, let’s suppose, you need to pass a large string in the form of a query string.
const redirectToAbout = () => {
navigate("/about?name=react is client side library", {
state: {
name: 'Programming Fields',
message: 'Message from home component',
},
});
};
Here, I have updated the query string. Now, check the result.
In the result, you can see the query string is encoded. The white space text is replaced with %20 string. Now, you have to decode it to get the actual string.
For decoding the query string, we can use the JavaScript predefined function-
- decodeURI()– This function will take the encoded query string and decode it to the actual string.
const location = useLocation();
useEffect(() => {
if (location.search) {
// perform any action
console.log('search', decodeURI(location.search));
}
}, [location]);
Let’s see the result now.
In the result, you will have the decoded query string.
So, that’s it for this post, I hope this basic concept will help you to use the useLocation hook in React app.
Leave a Reply