Detect location change in order to close a state¶
You have a modal or a dropdown in a header or footer component that's on every page.
Menu stays open when user clicks a link and state changes¶
User changes location.
You want it to close the modal/dropdown state when the state changes.
Problem: Menu stays open.
Use useLocation()
to detect state change and close the state¶
import { useLocation } from 'react-router-dom';
React.useEffect(() => {
setMenuOpen(false);
}, [location])
Full example¶
import React from 'react';
import { useLocation, Switch } from 'react-router-dom';
function FooView () {
const [isMenuOpen, setMenuOpen] = useState<boolean>(false);
const onClickCallback = useCallback((e: React.MouseEvent<HTMLDivElement>) => {
if (e) {
e.stopPropagation();
e.preventDefault();
}
setMenuOpen( !isMenuOpen );
}, [
isMenuOpen,
setMenuOpen
]);
import { useLocation } from 'react-router-dom';
React.useEffect(() => {
setMenuOpen(false);
}, [location])
return (
<div className={FOO_VIEW_CLASS_NAME}>
<button onClick={onClickCallback}>toggle menu</button>
{isMenuOpen ? (
<div className={`${FOO_VIEW_CLASS_NAME}-dropdown`}>
<Link to={ROUTE_HOME}>Home</Link>
</div>
) : null}
</div>
);
}