Uncaught error with useNavigate() only in the context of a <Router> component in React JS
P粉207969787
2023-08-26 12:55:20
<p><strong>I removed some code to make it easier to read</strong></p>
<blockquote>
<p>But everything is imported correctly and working fine but I can't resolve this error<strong>I got this error but I saw a tutorial and even reactRouter website has the same method but it's not working for me does not work in the code</strong></p>
</blockquote>
<p><strong>I want to change the route when the Enter key is pressed on the keyboard</strong></p>
<blockquote>
<p>This is the app.js file</p>
</blockquote>
<pre class="brush:php;toolbar:false;">function App() {
return (
<div>
<div key="navbar" className="navbar">
<Navbar />
</div>
<div key="search-box" className="search-box">
<SearchBar carddata={cards}/>
</div>
<div>
<Cards key="cards" carddata={cards} />
</div>
</div>
);
}
export default App;</pre>
<blockquote>
<p>This is the file where all the routing happens, when useNavigate changes the route it should open the route I want to open ('/SearchResult')</p>
</blockquote>
<pre class="brush:php;toolbar:false;">const Cards = ({ carddata: cardComponent }) => {
return (
//This is the file that should be opened when useNavigate changes the route to "/SearchResult"
<Route path="/SearchResult" element={<SearchResPage />}></Route>
</Routes>
<div className="right-section">
<RightCard cardData={cardComponent} />
</div>
</div>
</Router>
);
};
export default Cards;</pre>
<p><strong>This is the file that will change the route using useNavigate, the file I want to open is searchResPage (the code will be after this code)</strong></p>
<pre class="brush:php;toolbar:false;">import { useNavigate } from "react-router-dom";
const SearchBar = ({ carddata}) => {
const navigate=useNavigate();
//This is the function called by onKeyDown
function searchResult(e) {
if (e.key === "Enter") {
if (e.target.value === "") return;
//Used to change routing
navigate('/SearchResult')
//Used to filter the results passed from props and display them
carddata.filter((result) => {
if (`${result.heading}`.toLowerCase().match(e.target.value)) {
console.log(result)
}
});
}
}
return (
<div className="flex">
<input onKeyDown={searchResult} type="text" ></input>
</div>
);
};
export default SearchBar;</pre>
<blockquote>
<p>Or is there any other way to change the route when the enter key is pressed without refreshing the page? I can find this option but don't know why it doesn't work</p>
</blockquote><p><br /></p>
The error means you are trying to use the
useNavigate
hook outside ofRouter
. The most common is in thereact-router-dom
package, likeBrowserRouter
, and then you have theRoutes
andRoute
components.should look like this (Router can be in the App or in another file, such as
index.js
):Then your component should work fine.