I am currently working on a project using Ant Design
and on one page I have a dropdown Menu. When you click on the menu it opens the dropdown but if you scroll down the menu still keeps open. I wish to implement that when the user is scrolling down the menu closes.
I tried to implement a handleScroll()
function in order to use is with the provided prop onVisibleChange
. However I am not sure what I should add in the function to get it work.
handleScroll = (e) => {
window.addEventListener('scroll', () => {
console.log('scrolling');
})
}
<Dropdown onVisibleChange={visible => this.handleScroll(
console.log(visible)) } trigger={['click']} overlay={
<Menu>
<Menu.Item key="1"
onClick={() => this.scrollTo(this.whyRef)}>
<Icon icon={u1F427} /> <strong>WHY</strong>
</Menu.Item>
</Menu>
}>
<Dropdown>
I am currently working on a project using Ant Design
and on one page I have a dropdown Menu. When you click on the menu it opens the dropdown but if you scroll down the menu still keeps open. I wish to implement that when the user is scrolling down the menu closes.
I tried to implement a handleScroll()
function in order to use is with the provided prop onVisibleChange
. However I am not sure what I should add in the function to get it work.
handleScroll = (e) => {
window.addEventListener('scroll', () => {
console.log('scrolling');
})
}
<Dropdown onVisibleChange={visible => this.handleScroll(
console.log(visible)) } trigger={['click']} overlay={
<Menu>
<Menu.Item key="1"
onClick={() => this.scrollTo(this.whyRef)}>
<Icon icon={u1F427} /> <strong>WHY</strong>
</Menu.Item>
</Menu>
}>
<Dropdown>
Share
Improve this question
edited Jan 18, 2019 at 17:16
Thelouras
8801 gold badge11 silver badges30 bronze badges
asked Jan 18, 2019 at 17:09
FabianFabian
972 gold badges3 silver badges11 bronze badges
1 Answer
Reset to default 2You need to add the event listener in the constructor and handle the visibility state of the dropdown yourself. Try something like this:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: false
};
window.addEventListener("scroll", this.closeMenu);
}
toggleMenu = () => {
this.setState({ visible: !this.state.visible });
};
closeMenu = () => {
this.setState({ visible: false });
};
render() {
return (
<div>
<Dropdown
overlay={menu}
onVisibleChange={this.toggleMenu}
visible={this.state.visible}
trigger={["click"]}
>
<a className="ant-dropdown-link" href="#">
Click me <Icon type="down" />
</a>
</Dropdown>
</div>
);
}
}
Working example: https://codesandbox.io/s/2ovjzwqz9y