UseNavigate() may be used only in the context of a Router component – How To Fix It?

useNavigate() may be used only in the context of a Router component

When working with react-router-dom, you use the useNavigate() and get the following error message: “useNavigate() may be used only in the context of a Router component”. Let’s see how to solve this issue.

Why does the error occur?

In fact, the reason for the error is that the useNavigate() hook uses the context provided by the Router component, so it must be nested inside the Router. Therefore, when we use the useNavigate() hook outside React component’s scope, it throws an error.

Case of error

To illustrate, let me reproduce the error through the example below.

Example:

import { useNavigate } from 'react-router-dom';

export default function Demo() {
    const navigate = useNavigate();

    const handleClick = () => {
        console.log('Redirecting');
        navigate('/products');
    }

	return (
        <div>
          	<button className="btn btn-primary" onClick={handleClick}>Go to Products</button>
        </div>
    );
}
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import Demo from './Demo';

const root = ReactDOM.createRoot(document.getElementById('root')).render(<Demo />);

Output:

As we can see in the index.js file, we have not wrapped the ‘Demo’ component in a ‘Router’. This is why we are getting the above error message.

Solutions for error “useNavigate() may be used only in the context of a Router component

To fix the problem, all you need to do is to wrap all the components to use useNavigate() hook into your React component.

Let’s fix the error in the above example to help you understand the idea of ​​this approach. Open the index.js file and edit it as follows:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import Demo from './Demo';
import { BrowserRouter } from 'react-router-dom';

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

root.render(
    <BrowserRouter>
        <Demo />
    </BrowserRouter>
);

Import the <BrowserRouter> from react-router-dom and put the <Demo /> component inside the BrowserRouter component. Now we have fixed the error, you can use the useNavigate() hook normally. 

A note for you: 

Obviously, the index.js file is where you should wrap your entire React app inside a React component, since it’s the root file of your project.

After we wrap the whole application in React component, as a result, you can apply all the hooks that the react-router module provides to your components without worrying about errors.

Summary

In conclusion, with just a few minor adjustments, you can fix the erroruseNavigate() may be used only in the context of a Router component”. Thanks for your reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *