We have SPA and use react router v6 for navigation.
I have page with set of restricted urls for each page.
Is there any convenient way block navigation when user manually enter the part of url? For example,: http://localhost:0000/patrol user in address bar change http://localhost:0000/otherway and press enter. Can I prevent this navigation if /otherway is in set of restricted urls for current page?
I try to use beforeunload window event but it does not work stable.
const useBlockNavigation = (restrictedUrls: string[]) => {
const navigate = useNavigate();
const location = useLocation();
const [previousLocation, setPreviousLocation] = useState(location.pathname);
useEffect(() => {
const checkNavigation = (newPath: string) => {
return restrictedUrls.includes(newPath);
};
const handleNavigation = () => {
const newPath = location.pathname;
if (checkNavigation(newPath)) {
navigate(previousLocation);
} else {
setPreviousLocation(newPath);
}
};
window.addEventListener('popstate', handleNavigation);
const handleBeforeUnload = (event: BeforeUnloadEvent) => {
event.preventDefault();
event.returnValue = '';
};
window.addEventListener('beforeunload', handleBeforeUnload);
handleNavigation();
return () => {
window.removeEventListener('popstate', handleNavigation);
window.removeEventListener('beforeunload', handleBeforeUnload);
};
}, [location, navigate, restrictedUrls, previousLocation]);
};
const MyComponent = () => {
const restrictedUrlsForCurrentPage = ['/restricted-page-1', '/restricted-page-2'];
useBlockNavigation(restrictedUrlsForCurrentPage);
return (
<div>
<h1>Current Page</h1>
</div>
);
};
export default MyComponent;