0

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

3 Answers3

1

you can use "useHistory" hook.

import { useHistory } from 'react-router-dom';
const history = useHistory();

//call this method on button click
history.goBack();
Asad Gulzar
  • 403
  • 4
  • 8
0

Im not an expert with react but maybe you can try it like this.

      <button onClick={() => history.goBack()}>Back</button>
Hi1mNico
  • 45
  • 11
0

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.

Mursalin Malik
  • 57
  • 1
  • 12