I’m new to react-router-dom and I’m trying to use the useLocation() hook in my app. However, I keep getting the following error: “useLocation() may be used only in the context of a component”.
I’ve tried to fix this error by wrapping my app in a BrowserRouter, but then I end up with another error and I feel out of my depth.
Can someone please help me understand what I’m doing wrong and how to fix this error?
Thank you!
App.js File:
import { useState } from "react";
import {
BrowserRouter,
Switch,
Route,
useLocation,
useNavigate,
} from "react-router-dom";
import "./App.css";
import Header from "./Header";
import LandingPage from "./LandingPage";
import NavigationMenu from "./Navigation";
import Product from "./Product";
const products = [
{
name: "Product 1",
price: "£19.99",
image: "https://osofimages.s3.us-east-2.amazonaws.com/ZOOM/2018117_HR.jpg",
},
{
name: "Product 2",
price: "£29.99",
image: "https://osofimages.s3.us-east-2.amazonaws.com/ZOOM/2815694_HR.jpg",
},
{
name: "Product 3",
price: "£39.99",
image:
"https://www.hardwarestore.com/media/catalog/product/1/2/126043_1.jpg?quality=80&bg-color=255,255,255&fit=bounds&height=&width=",
},
];
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const location = useLocation();
const navigate = useNavigate();
function handleLogout() {
setIsLoggedIn(false);
alert("User has logged out");
navigate("/");
}
return (
<div className="App">
<Header isLoggedIn={isLoggedIn} onLogout={handleLogout} />
<BrowserRouter>
<NavigationMenu />
<Switch>
<Route exact path="/">
<LandingPage />
</Route>
<Route path="/shop">
<div className="products-container">
{products.map((product, index) => (
<Product
key={index}
name={product.name}
price={product.price}
image={product.image}
/>
))}
</div>
</Route>
</Switch>
</BrowserRouter>
</div>
);
}
export default App;