Skip to content

Latest commit

 

History

History
85 lines (54 loc) · 2.2 KB

README.md

File metadata and controls

85 lines (54 loc) · 2.2 KB

npm

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

Table of Contents

Dropdown

Extends Component

A dropdown component

Parameters

  • children is the element displayed on trigger
  • Link is the element displayed to trigger the dropdown

Examples

import { Dropdown } from 'preact-dropdown';

<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