I came back to react world after a few years. And things certainly have changed for good. I'm using MemoryRouter
for my app. And I can navigate fine by using Link
. But useNaviate
hook is not working as expected. It does nothing on the page. Could you please help me here? Here is my code:
Router:
<MemoryRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
</MemoryRouter>
Here is how I'm trying the navigation:
function Home() {
// demo purpose
const navigate = useNavigate()
navigate('/dashboard')
}
I'm not sure if I'm using it right, or if I need to do something else here.
CodePudding user response:
The problem was that I was calling navigate
directly when the component was rendering. It should either be called in an event, or it should be called in useEffect
hook.
CodePudding user response:
Make your navigate in function call or in useEffect like this:
function Home() {
// demo purpose
const navigate = useNavigate()
useEffect(() => {
navigate('/dashboard')
}, []);
}