override back botton on browser for a page in js react 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: chrome back button click event react
const {history} = useRouter();
useEffect(() => {
return () => {
if (history.action === "POP") {
history.replace(history.location.pathname, );
}
};
}, [history])