Last active
May 9, 2023 12:55
-
-
Save ms10596/8cc23ed9f220adea41fd4bcfd7840cf7 to your computer and use it in GitHub Desktop.
useBackForward is a react hook for navigating back and forward. The hook returns two functions for navigation and two boolean variables that detect if there's an available back and forward in order to have a better user experience.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from 'react'; | |
import { useLocation, useNavigate, useNavigationType } from 'react-router'; | |
export default () => { | |
const navigationType = useNavigationType(); | |
const location = useLocation(); | |
const navigate = useNavigate(); | |
const [currentIndex, setCurrentIndex] = useState(0); | |
const [routesLength, setRoutesLength] = useState(0); | |
const goBack = () => { | |
setCurrentIndex(currentIndex - 1); | |
navigate(-1); | |
}; | |
const goForward = () => { | |
setCurrentIndex(currentIndex + 1); | |
navigate(1); | |
}; | |
useEffect(() => { | |
if (navigationType === 'PUSH') { | |
let newLength = routesLength + 1; | |
setRoutesLength(newLength); | |
setCurrentIndex(newLength); | |
} | |
}, [location, navigationType]); | |
return { | |
canBack: currentIndex > 0, | |
canForward: currentIndex < routesLength, | |
goForward, | |
goBack, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment