-1

See my code below.

Error: useNavigate() may be used only in the context of a <Router> component.

My Code:

import { BrowserRouter, Route, Routes, useNavigate } from 'react-router-dom';
import MyNav from "./MyNav";
import Login from "./routes/Login"


function App() {

  const navigate = useNavigate();

  return (
    <div className="App">
      <MyNav />
      <BrowserRouter>
        <Routes>
          <Route path="/login" element={<Login />} />
        </Routes>
      </BrowserRouter>

      
    </div>
  );
}

export default App;

I'm trying to move login page but I get the error. i wrapped my component in Route with Routes and BrowserRouter. Why is useNavigate() function not working in my React?

daye
  • 7
  • 1

1 Answers1

0

The problem about this question is that you have to wrap this component with the BrowserRouter, because you are creating the BrowserRouter Context in this component and you can't use this hook outside this context.

The final code that you can check it is:

  • You need to create a parent component
// FILE: AppRouter.jsx

import {BrowserRouter} from "react-router-dom";
import {AppRoutes} from "./AppRoutes.jsx"

const AppRouter = () => {
   return <BrowserRouter>
            <AppRoutes />
          </BrowserRouter>
}
  • And create the child component that will manage routes of your application
// FILE: AppRoutes.jsx

import { Route, Routes, useNavigate } from 'react-router-dom';
import MyNav from "./MyNav";
import Login from "./routes/Login"

const AppRoutes = () => {
  const navigate = useNavigate();

  return (
    <div className="AppRoutes">
      <MyNav />
        <Routes>
          <Route path="/login" element={<Login />} />
        </Routes>
    </div>
  );

And now you can use useNavigate in your component

Adrian Naranjo
  • 862
  • 6
  • 14