[Fix] useNavigate() may be used only in the context of a component

The error “useNavigate() may be used only in the context of a component” is an error that is invoked whenever you are coding in react.js and trying to add a button .Given below is the snippet of the error, which you can find here:

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

I would like to share with you the steps I took to fix the “useNavigate() may be used only in the context of a component” in your project file.

Why useNavigate() may be used only in the context of a component Error is seen?

The error, “useNavigate() may be used only in the context of a component” is seen because you can’t use useNavigateuseLocation outside of the Router component.

The reason for this is because useNavigate uses useLocation for its functions, useLocation will fetch you a location within LocationContext. In case you would want to get the react context, you will have to render the component as a descendant of the context provider.

The detailed solution to fix the error “useNavigate() may be used only in the context of a component”, is given below:

How to fix the error, “useNavigate() may be used only in the context of a component”?

To fix the error, you have to wrap the component that uses the useNavigate hook in a Router.

To fix the error, “useNavigate() may be used only in the context of a component”, follow the steps given below:

Step 1: In case the environment which you are using is a browser, you will have to use BrowserRouterBrowserRouter is built based on Router.

Step 2: You will have to change your refactor to the below mentioned codes:

Change your App.jsx to the below mentioned code:

function App() {
  const navigate = useNavigate();
  return (
      <div>
        <button onClick={() => navigate(-1)}>go back</button>
        <Nav/>
        <Routes>
          <Route exact path="/" element={<Home/>}/>
          <Route exact path="/home" element={<Home/>}/>
          <Route exact path="/upcoming/:user" element={<Upcoming/>}/>
          <Route exact path="/record/:user" element={<Record/>}/>
          <Route path="*" element={<NotFound/>}/>
        </Routes>
      </div>
  );
}

Change your index.jsx to the below mentioned code:

import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';

ReactDOM.render(
  <BrowserRouter>
    <App/>
  </BrowserRouter>,
  document.getElementById('root')
)

This should fix the error, “useNavigate() may be used only in the context of a component”.

Conclusion

To fix the error “useNavigate() may be used only in the context of a component”, you have to wrap the component that uses the useNavigate hook in a Router. To achieve the following you have to follow the steps and also update your App.jsx and index.jsx