Navigate back and forward using Memory Router
React router is an amazing tool for routing in React. Using Browser Router can easily utilize the back and forward button of the browser. But what if you want to make a back and forward button in your electron app that are enabled and disabled automatically? Well, it is possible. In this article, we will see how to use the back and forward button in React Router.
Since there's no clear way to access the history stack of the memory router, we will store the information we need in a local state. We'll create a small custom hook that will handle the logic of:
- Navigating back.
- Navigating forward.
- Checking if we can navigate back.
- Checking if we can navigate forward.
Now let's jump to the code. We'll use 3 hooks from react-router-dom.
- useLocation: This will give us the current location.
- useNavigate: This will give us the navigate function.
- useNavigationType: This will give us the navigation type. It can be PUSH, POP or REPLACE. We'll only increase the
routesLength
if the navigation type isPUSH
.
We'll also need now two states.
- Routes Length: This wil store the length of the traversed routes. Initially it's 0 and increased by one when we navigate.
- Current Index: This will store the current index of the route. Initially it's 0, increased by one when we navigate forward and decreased by one when we navigate back.
import { useEffect, useState } from 'react';
import { useLocation, useNavigate, useNavigationType } from 'react-router';
export default function useDynamicBackForward() {
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
};
}
Now we can use this hook in our component. We'll use the canBack
and canForward
to enable and disable the back and forward button. And we'll use the goBack
and goForward
to navigate back and forward.
Hope this helps. Happy coding.