MD FAHIM
MD FAHIM

Reputation: 39

How to use useLocation hook of React Router DOM v6?

<div
  className={`alert alert-${showAlert?.color} alert-fixed fade ${
    showAlert ? "show" : "d-none"
  }`}
  role="alert"
  style={{
    width: "450px",
    right: "1%",
    top: "15%",
    bottom: "unset",
    left: "unset",
    transform: "unset",
  }}
>
  <div className="d-flex justify-content-between">
    <strong>{showAlert?.msg}!</strong>
    <button
      type="button"
      className="btn-close"
      onClick={() => setShowAlert(false)}
    ></button>
  </div>
</div>

Upvotes: 2

Views: 27813

Answers (2)

Guneet Thind
Guneet Thind

Reputation: 41

First you have to import the useLocation hook

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

then set

const location = useLocation();

now you can use the location object which has the following properties: key, pathname, search, hash, state

{
  key: 'ac3df4', // not with HashHistory!
  pathname: '/somewhere',
  search: '?some=search-string',
  hash: '#howdy',
  state: undefined
}

Here's another demo screenshot to what location object looks like:

console.log of 'location' object

Upvotes: 2

lakimapturn
lakimapturn

Reputation: 92

You can import the useLocation hook into your project using

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

If you want to read about it you can use this article:

https://www.geeksforgeeks.org/react-router-hooks/

Upvotes: 0

Related Questions