Reputation: 753
I'm creating a Dropdown
menu using React.
But I've no idea how to implement handleClose()
.
I want:
<Dropdown>
=> handleClose()
<ActionMenu>
=> handleClose()
<ActionMenu>
=> handleClose()
if preventDefault()
was not called<ActionMenu enabled={false}>
=> do nothing<ActionMenu enabled={false}>
=> do nothing<ActionMenu>
=> do nothing<NonActionMenu>
=> do nothing<NonActionMenu>
=> do nothing<Dropdown>
lost focus (onBlur=
) because an element outside dropdown got focus => handleClose()
<Dropdown>
lost focus (onBlur=
) because an element inside dropdown got focus => do nothingImplementing <Dropdown onBlur={() => handleClose()} ...>
works for point 9 but failed for point 10.
Can you suggest your idea?
I've no sandbox because the project is quite complex.
But you can fork & modify here: my project
Upvotes: 2
Views: 172
Reputation: 435
For the click, you can add an event listener to the window object to take care of any click outside the dropdown wrapper. You can also modify this for the enter key:
window.addEventListener('click', function(e) {
const dropDownWrapper = document.querySelector('#id of dropdown wrapper');
const path = e.path || (e.composedPath && e.composedPath());
if (!path.some(x => !(x instanceof SVGElement) && x.id && x.id === '#id of dropdown wrapper')) {
dropDownWrapper.querySelector('.class of dropdownlist') ?
x.querySelector('.class of dropdownlist').style.display = 'none' : null
} else{
dropDownWrapper.querySelector('.class of dropdownlist') ?
x.querySelector('.class of dropdownlist').style.display = 'block' : null
}
}, true);
Upvotes: 1