I'm trying to create a back button with react
this is my function
<button onClick={() => navigate(-1)}>
But it is working only on the second click not the first one
I'm trying to create a back button with react
this is my function
<button onClick={() => navigate(-1)}>
But it is working only on the second click not the first one
you can use "useHistory" hook.
import { useHistory } from 'react-router-dom';
const history = useHistory();
//call this method on button click
history.goBack();
Im not an expert with react but maybe you can try it like this.
<button onClick={() => history.goBack()}>Back</button>
If you are using react-route-dom
v5 then you can do something like this.
By using this you can go back to the previous route added in history. Or it'll use history.goBack()
by default.
<button onClick={() => {
if (history.location.state && history.location.state.prevRoute) {
history.push(history.location.state.prevRoute);
} else {
history.goBack();
}
}}>
Back
</button>
Or you cna refer to this answer for v6.