Skip to content
  • Homepage
  • HTML
  • CSS
  • Symfony
  • PHP
  • How to
  • Contact
  • Donate

Teach Developer

Articles, Guides & Tips

How to Use useLocation Hook in React Router DOM V6

Home  »  React • How to • Tips   »   How to Use useLocation Hook in React Router DOM V6
Posted on September 17, 2022September 17, 2022
841

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.

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 favorite 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.

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(Home.jsx), 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: 'Home',
            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 the About component with some props.

Now, in the About component, we will capture these props using the useLocation hook.

So, let’s understand in the below snippet.(About.jsx)

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 check the result first. I have logged the location object in the console.

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.

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: 'Teach',
            message: 'Message from home component',
        },
    });
  };

So, that’s it for this post, I hope this basic concept will help you to use the useLocation Hook in React app.

React, How to, Tips

Post navigation

Previous Post: How to Delete Unused Database Tables in WordPress
Next Post: How to change password in the CodeIgniter framework

Related Posts

  • How to increase browser zoom level on page load with CSS?
  • How to make the div move up and down when scrolling the page with CSS?
  • How to Create Live Search in HTML table with jQuery
  • Enable or Disable SSH Root Login Access in Linux
  • How to Search Recently Modified Files in Linux
  • Understanding State in React Components

Categories

  • Codeigniter (3)
  • CSS (11)
  • eCommerce (1)
  • Framework (1)
  • Git (3)
  • How to (43)
  • HTML (5)
  • JavaScript (15)
  • Jquery (7)
  • Laravel (1)
  • Linux (4)
  • Magento-2 (1)
  • Node js (4)
  • Others (2)
  • PHP (11)
  • React (13)
  • Server (1)
  • SSH (3)
  • Symfony (6)
  • Tips (16)
  • Top Tutorials (10)
  • Ubuntu (3)
  • Vue (1)
  • Wordpress (7)

Latest Posts

  • What is SSH in Linux?
  • How to Delete Files in Ubuntu Command Line
  • How to Deploy a React application on a cPanel
  • How to use events listeners and Event Subscriber in Symfony
  • How to Convert PHP CSV to JSON

WEEKLY TAGS

AJAX (1) Codeigniter (1) Javascript (11) JQuery (1) PHP (16) Programming (1) React (3) Symfony (1)

Random Post

PHP 8.1: read-only properties
ReactJs Properties
Understanding State in React Components
Difference between var, let, and const in JavaScript
How to clear your cache in npm

Quick Navigation

  • About
  • Contact
  • Privacy Policy

© Teach Developer 2021. All rights reserved