Reputation: 335
I want to close sidebar menu when the user has selected a new target URL. With react-router-dom, how can I detect when the user navigates to a new page?
<div className="" id="rightMenu">
<div className="sidebar_link">
<a href="#" id="personal_account"
onClick={() =>
this.props.history.push('/personal-account')}
Personal Account
</a>
</div>
<div
Upvotes: 1
Views: 1569
Reputation: 203417
You can create a history listener using history.
If using react-router-dom v4/5/6:
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
// Listen for changes to the current location.
const unlisten = history.listen((location, action) => {
// location is an object like window.location
console.log(action, location.pathname, location.state);
});
// To stop listening, call the function returned from listen().
unlisten();
I wrap this up in an useEffect
hook
useEffect(() => {
const unlisten = history.listen((location, action) => {
// logic to close sidebar
});
return () => {
unlisten();
}
}, []);
If still using a class-based component you can achieve the same by using the componentDidMount
lifecycle method to add the listener, and the componentWillUnmount
lifecycle method to clear it out.
this.unlisten = null;
componentDidMount() {
this.unlisten = history.listen((location, action) => {
// logic to close sidebar
});
}
componentWillUnmount() {
this.unlisten();
}
Upvotes: 1
Reputation: 141
You should do something like this:
const [isMenuVisible, setIsMenuVisible] = useState(true)
return(
<RightMenu className="" id="rightMenu" isVisible={isMenuVisible}>
<div className="sidebar_link">
<a href="#" id="personal_account"
onClick={() => {
setIsMenuVisible(false)
this.props.history.push('/personal-account')}
}>
Personal Account
</a>
</div>
</RightMenu>
)
const RightMenu = styled.div<{ isVisible: boolean }>`
display: ${({ isVisible }) => isVisible?'flex':'none'};
`
Upvotes: 1