'Error: useLocation() may be used only in the context of a <Router> component
I have installed react-router-domV6-beta.
By following the example from a website I am able to use the new option useRoutes I have setup page routes and returning them in the App.js file.
After saving I am getting the following error:
Error: Error: useLocation() may be used only in the context of a component.
App.js
import "./App.css";
import react, { useState, useEffect } from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import _ from "lodash";
import Cast from "./Cast";
import list from "./list";
import Footer from "./Footer";
import DetailLayout from "./DetailLayout";
function App() {
const [charnames, setCharnam] = useState("");
function charname(names) {
setCharnam(names);
}
function castDetail(everycast) {
return (
<Cast
key={everycast.id}
url={everycast.url}
name={everycast.name}
castp={charname}
/>
);
}
const cc = charnames;
const p = "/" + cc;
//const p="/haha h";
const res = p.replace(/ /g, "");
return (
<div className="App">
<div className="overview">{list.map(castDetail)}</div>
{/* <DetailLayout /> */}
{console.log(charnames)}
<Router>
<Cast />
<Routes>
<Route exact path={res} element={<DetailLayout />} />
</Routes>
</Router>
<Footer />
</div>
);
}
export default App;
Cast.js
import react from "react";
import { NavLink } from "react-router-dom";
export default function Cast(props) {
function setpath() {
props.castp(props.name);
}
const path = "/" + props.name;
return (
<div className="cast">
{/* <Link to="/about">About</Link> */}
{/* <NavLink to="/about">About</NavLink> */}
<NavLink to={path}>
<img onClick={setpath} src={props.url} />{" "}
</NavLink>
<p>{props.name}</p>
</div>
);
}
Solution 1:[1]
this error simply says wrap your useLocation() inside
<Router> </Router>
all react-router-dom hooks and functions should be used inside
<BrowserRouter> </BrowserRouter>
otherwise they simply don't work
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rugved Patel |