How to fix the "useNavigate() may be used only in the context of a <Router> component" error in React

I recently came across this error while trying to do programmatic navigation in React and wanted to write this down for my future self, in case I run into this again.

Usually, you will want to use the useNavigate() hook instead of useHistory in the latest version of react router. However, you have to make sure it's being used inside a <Router> component.

To fix this, you will want to wrap your component, say in your App.js(x), with Routes like so:

<Routes>
            <Route path="/" element={<Layout />}>
                <Route index element={<Home handleClick={handleClick} />} />
                <Route path="/list" element={<List data={data} />} />
                <Route path="/add-item" element={<AddItem />} />
            </Route>
</Routes>

To ensure that this works, you'll want to ensure you've imported Routes, Route and useNavigate at the top of your App.jsx file like so:

import { Routes, Route, useNavigate } from 'react-router-dom';

Once you've got that in place, you will go to your index.js(x), import BrowserRouter from react-router-dom, and wrap your App with a BrowserRouter, like so:

const rootElement = document.getElementById('root');
const root = createRoot(rootElement);

root.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>,
);

And voila! This should resolve your issue and you should be able to use useNavigate for redirection now.

Thank you for reading! :)