preact-dropdown
v0.0.2
Published
A simple dropdown component
Downloads
27
Readme
preact-dropdown
A dropdown component written with preact.
Cool thing here is that the dropdown will "deactivate" when clicked outside of it.
Important thing to know may be that a click event is registered for every DropDown instance.
Install
yarn add preact-dropdown
API
Dropdown
Extends Component
A dropdown component
Parameters
children
is the element displayed on triggerLink
is the element displayed to trigger the dropdown
Examples
<DropDown Link={Button}>
<div>
My inner content
</div>
</Dropdown>
DropReplace
Extends Dropdown
Works just like DropDown but replaces the Link with the children content
How it works
If you prefer a custom implementation and just wanted the "click outside" feature here's the handleClick event ; the else if bracket is the part where the outside clicking takes place.
It crawls up every element from the element we clicked and if the target is not the base element at any moment, it triggers a close.
handleClick = ({ target }) => {
if (target===this.base.firstChild)
this.toggle();
else if (this.state.open) {
do {
if (target===this.base) return;
} while ((target=target.parentNode));
this.close();
}
}
Because of the wrapping div we check the .firstChild which is the provided Link.
(target===this.base.firstChild)
License
Original snippet taken from preact website
Code was only changed and packaged for generic usage
MIT License © Patrick Borowy