Suppose I have following code:
const [showChild1, setShowChild1] = useState(false)
const [showChild2, setShowChild2] = useState(false)
<ParentComponent>
{showChild1 && <Child1 />}
{showChild1 && <Child2 />}
....
</ParentComponent
Suppose I am viewing Child2 in my browser, but I want to go back to see Child1. How can I use the browser's back and forward buttons to navigate between conditionally rendered components? As of now when i click on the back button im pushed to path /.
You can add event listeners to the global window object. The event name is "popstate", here is the code example:
useEffect(() => {
window.history.pushState(null, null, window.location.pathname);
window.addEventListener('popstate', yourEvent);
return () => {
window.removeEventListener('popstate', yourEvent);
};
}, []);
use onpopstate event to handle browser navigation options.