How To Solve Error “useLocation() May Be Used Only In The Context Of A Router Component”

useLocation() may be used only in the context of a Router component

If you are getting the error “useLocation() may be used only in the context of a Router component”, let’s read this article. What is the reason, and how to solve this problem? Go into detail now.

What is the reason for this error?

The problem happened when you did not use useLocation inside the Router context in react-router. React-Router is a standard routing library in React. It keeps the app’s interface in sync with the browser URL. Your useLocation hook will use the thing that Routes provide so it has to wrap inside Router.

Example for Error:

import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { Routes } from "react-router-dom";
import React from "react";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render (
    <React.StrictMode>
    	<App />
    </React.StrictMode>
);

The solution for error “useLocation() may be used only in the context of a Router component”

To solve this problem, you can wrap in Router component.

Example :

import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { Routes } from "react-router-dom";
import React from "react";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render (
    <React.StrictMode>
      	<App />
    </React.StrictMode>
);

And you can use “useLocation” hook in your “App.js” file

Example :

import React from "react";
import { useLocation } from "react-router-dom";
 
const App = () => {
    const location = useLocation();

    return (
        <div>
            <button onClick={() => { console.log(location); }}>
              	Click Me
            </button>
        </div>
    );
};
export default App;

Summary

In this tutorial, I have shown and explained how to fix the error “useLocation() may be used only in the context of a Router component”. So, if you are using useLocation hook and get that error, you should use the ‘useLocation’ hook inside the Router. Thank you for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *