TL;DR
I wanted to challenge myself to build a custom dropdown component that works with HTML forms and looks the same on all platforms and browsers. I finally managed to make one, and here is how...
Code
The code can be found on this Code Pen.
How it's done
- Create a native web component that extends HTML Element.
- Give it the ability to have multiple themes (using pre-defined colors in CSS).
- Allow to set its items either using
setAttribute
or by firing an event which has the items in it. - Listen to a custom event indicating when an item is selected.
- Give it the ability to be a part of any HTML form. Note that
element-internals-polyfill
is needed for this to work on some browsers such asSafari
at the time of writing this article.
UI of the dropdown component
It is composed of three elements.
- a read-only
input
element which displays the currently selected item. - a (initially hidden)
div
which contains the items in the dropdown menu. - an icon to indicate the state of the dropdown (open or closed). Note that the
svg
used is adapted from Bootstrap icons.
Business logic
- When connected, display the component in its selected theme. Choose the default one if none is selected.
- Register the
dropdown
anditem selected
events passed when declaratively creating the component. - Once the
dropdown
event is fired, capture the items and add them to the list. - Give the ability to set the selected item programatically. This is particularly useful when the currently selected item is pre-known for the service provider. For instance, a list of locations in a booking site and it should ideally display the current city at which the user resides.
How it looks
Conclusion
We created a modern customizable dropdown component using the tools available to the browser and it looks the same everywhere. Feel free to let me know if you have any additions or questions.
Happy developing!