Home > OS >  useLocation returns undefined
useLocation returns undefined

Time:04-15

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

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?

CodePudding user response:

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>
  );
}
  • Related