react redirect to previous page code example
Example 1: react router last page
import { useHistory } from "react-router-dom";
function demo () {
let history = useHistory();
const goToPreviousPath = () => {
history.goBack()
}
return (
<div>
<Button
onClick={goToPreviousPath}
>
Back
</Button>
</div>
):
}
Example 2: how to redirect back to previous page onClick react router
import { useHistory } from 'react-router-dom';
function app() {
let history = useHistory();
const redirect = () => {
history.push('/your-path')
}
return (
<div>
<button onClick={redirect}>Redirect</button>
</div>
)
}
Example 3: how to redirect back to previous page onClick react router
import React from 'react'import { Redirect } from 'react-router-dom'class MyComponent extends React.Component { state = { redirect: false } setRedirect = () => { this.setState({ redirect: true }) } renderRedirect = () => { if (this.state.redirect) { return <Redirect to='/target' /> } } render () { return ( <div> {this.renderRedirect()} <button onClick={this.setRedirect}>Redirect</button> </div> ) }}