Borislav Hadzhiev
Wed Apr 20 2022·2 min read
Photo by Mats Hagwall
The error "useHref() may be used only in the context of a Router component" occurs when we try to use a Link component outside of the Router context in react router. To solve the error, use the Link component only within the Router context.
import React from 'react'; import {BrowserRouter as Router, Route, Link, Routes} from 'react-router-dom'; export default function App() { // 👇️ make sure to use your Links ONLY within a <Router> context return ( <Router> <div> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> </ul> </nav> </div> </Router> ); }
We imported BrowserRouter as Router
from the react router package and wrapper
our Link
components in the Router context.
This is necessary because the Link
component relies on the context that the
Router
component passes down.
Router
component. Make sure that all components in which you use links are nested inside of a Router
.If you use the Jest testing library, the solution is the same. You have to
wrap any components that use the Link
component in a Router
.
import {render} from '@testing-library/react'; import App from './App'; import {BrowserRouter as Router} from 'react-router-dom'; test('renders react component', async () => { render( <Router> <App /> </Router>, ); // ... your tests here });
The App
component uses the Link
component, so in order to render it we have
to wrap it in a Router, otherwise the context that links rely on is not
available.
A good place to wrap your React.js application with the Router component is in
your index.js
file.
import {createRoot} from 'react-dom/client'; import App from './App'; import {BrowserRouter as Router} from 'react-router-dom'; const rootElement = document.getElementById('root'); const root = createRoot(rootElement); root.render( <Router> <App /> </Router> );
Once the entry point of your React application is wrapped with the Router
component, you'll be able to use the Link
component anywhere in your app.