react router browser back button code example
Example 1: if back react
import { useHistory } from 'react-router-dom'
const [ locationKeys, setLocationKeys ] = useState([])
const history = useHistory()
useEffect(() => {
return history.listen(location => {
if (history.action === 'PUSH') {
setLocationKeys([ location.key ])
}
if (history.action === 'POP') {
if (locationKeys[1] === location.key) {
setLocationKeys(([ _, ...keys ]) => keys)
} else {
setLocationKeys((keys) => [ location.key, ...keys ])
}
}
})
}, [ locationKeys, ])
Example 2: react router native back button
<BackButton />
Connects the global back button on Android and tvOS to the router’s history. On Android, when the initial location is reached, the default back behavior takes over. Just render one somewhere in your app.