If you’ve ever faced the following error in React:
useNavigate() may be used only in the context of a component
This error throws in useNavigate hook.
This happens because the useInRouterContext will check if the component(which uses useNavigate
hook) is a descendant or a child of a <Router>
component. If it’s not, then the above error will be thrown.
uses useNavigate
useLocation
underly,
will get the location from LocationContext provider. If you want to get the react context, you should render the component as the descendant of a context provider. useLocation
Router
component use the LocationContext.Provider and NavigationContext.Provider. That’s why you need to render the component as the children, so that
hook can get the context data from useNavigate
NavigationContext
and LocationContext
providers.
Solution
To fix the above error, we need to wrap our root component with React Router component, which could be: BrowserRouter, MemoryRouter or HistoryRouter as the following:
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
ReactDOM.render(
<BrowserRouter>
<App/>
</BrowserRouter>,
document.getElementById('root')
)
function App() {
const navigate = useNavigate();
return (
<div>
<button onClick={() => navigate(-1)}>go back</button>
<Nav/>
<Routes>
<Route exact path="/" element={<Home/>}/>
<Route path="*" element={<NotFound/>}/>
</Routes>
</div>
);
}
Photo from Unsplash