Sometimes, we want to use Redirect in the new react-router-dom.
In this article, we’ll look at how to use Redirect in the new react-router-dom.
How to use Redirect in the new react-router-dom?
To use Redirect in the new react-router-dom, we can check if we want to redirect.
If we do, then we render the Redirect component.
For instance, we write
class MyComponent extends React.Component {
state = {
redirect: false,
};
handleSubmit = async () => {
await axios.post(/**/);
this.setState({ redirect: true });
};
render() {
const { redirect } = this.state;
if (redirect) {
return <Redirect to="/somewhere" />;
}
return <RenderYourForm />;
}
}
to create the handleSubmit function that sets the redirect state to true.
And if redirect is true, we return the Redirect component to redirect in the render method.
Conclusion
To use Redirect in the new react-router-dom, we can check if we want to redirect.
If we do, then we render the Redirect component.