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.
yarn add preact-dropdown
Extends Component
A dropdown component
children
is the element displayed on triggerLink
is the element displayed to trigger the dropdown
import { Dropdown } from 'preact-dropdown';
<Dropdown Link={Button}>
<div>
My inner content
</div>
</Dropdown>
Extends Dropdown
Works just like DropDown but replaces the Link with the children content
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)
Original snippet taken from preact website
Code was only changed and packaged for generic usage
MIT License © Patrick Borowy