The error displayed:
Uncaught Error: useNavigate() may be used only in the context of a <Router> component.
at invariant (index.tsx:24:1)
at useNavigate (index.tsx:512:1)
at Login (Login.js:13:1)
at renderWithHooks (react-dom.development.js:14985:1)
at mountIndeterminateComponent (react-dom.development.js:17811:1)
at beginWork (react-dom.development.js:19049:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at beginWork$1 (react-dom.development.js:23964:1)
I'am just starting a new react project and doing basic routing however an error is cause by the use of useNavigate, I used to the same many times and I don't know what I'm missing:
App.js:
import {BrowserRouter, Route, Routes} from "react-router-dom";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path='/' element={<Login/>} exact/>
<Route path={"/chat/:room"} element={<Chat/>} socket={socket} exact/>
</Routes>
</BrowserRouter>
);
}
Login.js:
import {useNavigate} from "react-router"
function Login() {
const navigate = useNavigate()
const [error, setError] = useState("")
const validationSchema = yup.object({
username: yup.string("username must be a string").required("username is required"),
password: yup.string("password must be a string").required("password is required")
})
const onSubmit = async () => {
const user = {
username: formik.values.username,
password: formik.values.password
}
const res = await api.post('/login', formik.values)
if (res === true){
localStorage.setItem('user', JSON.stringify(user));
navigate("chat/1");
}
else
setError("username or password incorrect");
}
const formik = useFormik({
initialValues: {
username: '',
password: ''
},
onSubmit,
validationSchema
})
...
}