Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useLocation returns undefined

I use useLocation hook in my app from react-router-dom v5. However, it always returns me undefined. Here is the minimal setup to reproduce this issue.

App.js

import { Route, NavLink as Link, Switch, useLocation } from "react-router-dom";

export default function App() {
  const { location } = useLocation();
  console.log(location);
  return (
    <div>
      <div
        style={{
          display: "flex",
          backgroundColor: "cadetblue",
          alignItems: "center",
          columnGap: "10px"
        }}
      >
        <h1>Menu</h1>
        <Link to="/invoices">Go to invoices</Link>
        <Link to="/eshop">Go to eshop</Link>
      </div>

      <Switch>
        <Route path="/invoices">
          <h2>Invoices</h2>
        </Route>
        <Route path="/eshop">
          <h2>Eshop page</h2>
        </Route>
      </Switch>
    </div>
  );
}

index.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { createRoot } from "react-dom/client";
import { MemoryRouter as Router } from "react-router-dom";

import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <Router>
    <App />
  </Router>
);

code sandbox: https://codesandbox.io/s/hungry-cloud-i2hui2?file=/src/App.js

Any ideas?

>Solution :

You should modify your { location } to location

import { Route, NavLink as Link, Switch, useLocation } from "react-router-dom";

export default function App() {
  const location = useLocation(); //removed brackets
  console.log(location);
  return (
    <div>
      <div
        style={{
          display: "flex",
          backgroundColor: "cadetblue",
          alignItems: "center",
          columnGap: "10px"
        }}
      >
        <h1>Menu</h1>
        <Link to="/invoices">Go to invoices</Link>
        <Link to="/eshop">Go to eshop</Link>
      </div>

      <Switch>
        <Route path="/invoices">
          <h2>Invoices</h2>
        </Route>
        <Route path="/eshop">
          <h2>Eshop page</h2>
        </Route>
      </Switch>
    </div>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading