unknownuserpprofile
unknownuserpprofile

Reputation: 31

use navigate not working for the first time

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

Upvotes: 1

Views: 680

Answers (4)

sadegh akbari
sadegh akbari

Reputation: 1

For react-router-dom to detect you from the route map, you must have nested routing If all your paths are not nested, use the code below

<button onClick={() => navigate(-2)}>

Upvotes: 0

Mursalin Malik
Mursalin Malik

Reputation: 57

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.

Upvotes: 0

Asad Gulzar
Asad Gulzar

Reputation: 672

you can use "useHistory" hook.

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

//call this method on button click
history.goBack();

Upvotes: 0

Hi1mNico
Hi1mNico

Reputation: 75

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

      <button onClick={() => history.goBack()}>Back</button>

Upvotes: 0

Related Questions