The error displayed:
useNavigate()
may be used only in the context of a<Router>
component.
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:
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
})
...
}