1

If user has navigated to another route, he can be navigated back to the previous page. If user has navigated back, he can be navigated forward to the previous page.

In react-native, react-nativation provides useNavigation hook so I can simply perform:

import React from 'react'
import { useNavigation} from 'react-navigation'

function Test()
{
    const navigation = useNavigation()
    return (
       
        <div>
            { navigation.canGoBack() && <button onClick=(() => navigation.goBack())>Go Back</button>
        </div>
        
    )
}

in ReactJS, react-router provides useHistory hook so I can perform history.goBack() but not history.canGoBack().

import React from 'react'
import { useHistory } from 'react-router'

function Test()
{
    const history = useHistory()
    return (
       
        <div>
            { history.canGoBack() && <button onClick=(() => history.goBack())>Go Back</button>

            {/* history.canGoBack() is not a function  */}

        </div>
        
    )
}

Does react-router provide a method to let us know if we can go back or forward?

anonym
  • 3,202
  • 6
  • 32
  • 56
  • I've deleted my answer because it doesn't solve the question. The first answer on this question looks promising: https://stackoverflow.com/questions/37385570/how-to-know-if-react-router-can-go-back-to-display-back-button-in-react-app – Lionel Rowe Oct 05 '20 at 12:20

1 Answers1

0
import {History} from 'react-router';
var canGoBack = (History.length > 1);

Can you please try this one? I think this may solve the issue.

  • Yes, that works fine for navigating back. What about forward? There must be a better approach for both. – anonym Oct 05 '20 at 12:06