useHref() may be used only in the context of a Router component
The “Uncaught error: useHref() may be used only in the context of a <Router> component” occur in React when we use <Link> component outside the Router context in React Router. To solve this issue, we have to wrap the <Link> component by the <Router/> component.
Let us explain its solution with below sample code.
import React from 'react';
import {BrowserRouter as Router, Route, Link, Routes} from 'react-router-dom';
export default function App() {
return (
<>
<Router>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</Router>
</>
);
}
function Home() {
return <p>Home</p>;
}
function Contact() {
return <p>Contact</p>;
}
In the above code, we have imported BrowserRouter as Router
from react-router-dom
. Next, all <Link>, <Routes> and <Route> with <Router> component. Thus, the error was resolved.
We can make some modifications to this code and can add a Router component in the index.js file. The index.js is the better place to add the Router component because it is the entry file of the whole application. So we can wrap the entire <App/> component with the <Router> component in index.js. So that we can use all components and hooks from React Router anywhere in the application. The below code explains how to use Router in index.js.
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import {BrowserRouter as Router} from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>
);
Here imported {BrowserRouter as Router}
from react-router-dom
. And wrapped <App/> component with <Router> component.
A <Link> is a component from react-router-dom that the user navigates to another route by clicking on it. A <Link> component renders an accessible <a> element with a href attribute that points to the given route. We pass the path as a value to the ‘to’ prop in the <Link> component.
The useHref hook returns a URL that may be used to link to the given location. The <Link> component uses useHref() hook internally for determining its own href value. That is why if we miss the <Router> component wrapping, React shows an error like “useHref() may be used only in the context of a <Router> component”.
Conclusion
To solve “Uncaught error: useHref() may be used only in the context of a <Router> component” in React, wrap the <Link> component by the <Router/> component which is imported from react-router-dom. It is better to wrap the whole <App/> component with the Router component so that we can use all components and hooks from React Router anywhere in the application.