Reputation: 465
I'm new to React, and most of the tutorials I see about redirecting using React Router seem to be using the aforementioned snippet. What I am trying to achieve is to redirect the user to the home page of my website upon successful login. I have tried history.push but according to my google searches, it doesn't work in Router v4 anymore. What can I do as an alternative? I'm open to both stateful and stateless solutions.
To clarify, here's the workflow -
Upvotes: 5
Views: 8638
Reputation: 1
you can use useNavigate function to navigate to the other page by simply using useNavigate from react-router-dom and navigate to the page you want first import it from react-router-dom library
import { useNavigate } from "react-router-dom";
export default function login() {
const navigate = useNavigate();
const handleSubmit = () => {
navigate("/routeName_that_you_wish_to_navigate_to");
}
return (
<>
<Button
type="submit"
text="Submit"
onCLick={() => handleSubmit()}
/>
</>
);
}
Upvotes: 0
Reputation: 1073
import { useNavigate } from "react-router-dom";
export default function navigationExample() {
const navigate = useNavigate();
return (
<>
<Button
type="ice"
text="WHITELIST"
onCLick={() => navigate("/login")}
/>
</>
);
}
Upvotes: 1
Reputation: 1443
history.push('./path')
is still usable in React Router v4 you need to add withRouter
example
import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import compose from 'recompose/compose'
class Test extends Component {
render () {
const { history } = this.props
return (
<div>
<Button onClick={() => history.push('./path')}
</div>
)
}
}
export default compose(
withRouter,
)(Test)
Upvotes: 1
Reputation: 2483
You can use the Redirect component. https://reacttraining.com/react-router/web/api/Redirect
Upvotes: 0