Skip to content

Building Search Input Web Component

Last updated on March 1, 2021

In this week of building anything with JavaScript,we’ll be going to build search input web component.

Introduction

How it would look like? Yeah, well it’s a plain input control with filtered option is also attached.

You use this feature every day either from Mobile or PCs. Yes, Google search where I got inspired to build this component.

I am pretty much excited while building this component why because this little piece we encounter very often in our programming subject.

Building Search Input Web Component

Idea here is to build a searchable text along with the given list of data and showing the desired property value as the display result to the end user.

This article assumes you already have prior experience of building web components with JavaScript, so I skip over the basic things that required to get started.

Here, the most functional piece of this component is to have a Search function where we do filtering process with the given input.

We have connected the below onSearch method with the Input element through input event. Input event is very much cleaner way of handling value change.

/**
   * To search element
   * @param {Event} event
   */
  onSearch(event) {
    const text = event.target.value;
    if (text !== '') {
      if (this._list && this._list.length) {
        const filteredValues = this._list.filter((data) => {
          if (data && !!this.displayField) {
            return data[this._displayField].toLowerCase().includes(text.toLowerCase());
          }
        });
        filteredValues && filteredValues.length && this.bindFilteredUser(filteredValues);
      }
    } else {
      this.collapseListElement();
    }
  }

What You Need To Know?

What Kind Of Shadow DOM it is?

We use Open Shadow DOM to provide much flexibility for the developer in order to customize it as they wish.

Do We Use Slot?

We are not allowing either default or named slots. The slot is to provide us to inject the HTML template as the child of this web component.

Any Observed Attributes?

Yes. This component aims to provide the filtering capability with the given list which results displayField and list are the 2 Observed Attributes that we expose.

Finally Our built Web Component would look like,

Search Input Web Component
Search Input Web Component
Published inAngularFrameworksJavaScriptReact