Implementing Filter and the Clear Filter Component

Explore how we can improve search results and user experience by adding a way to filter the dataset based on facets using the RefinementList component. Also, we add a way to clear applied filters using the ClearRefinements component.

Overview

In the previous lesson, we added a stats feature to our search functionality. This feature displays the number of results based on the searched query to the user.

In this lesson, we will look into adding the RefinementList and ClearRefinements components. RefinementList refers to filters that are set up as a way for the user to refine the results even further based on a set of specific attributes. The ClearRefinements component works as a way to clear the filters that have been applied.

The RefinementList component

The RefinementList component is used to filter the dataset based on facets selected by the user.

In order to use the component, any attribute value that we set in the component must be added to attributes for faceting which can be done by either using the dashboard or the API.

<RefinementList
      attribute="category"
      limit={4}
      showMore
      transformItems={(items) => {
        return items.map((item) => {
             return {
                  ...item,
                  label: `${item.label} (${item.count})`,
              };
         });
      }}
/>

Using the dashboard

To add an attribute to the list of Attributes for faceting,

  1. Go to the Configuration tab under the selected index.
  2. Click on Facets.
  3. Then add attributes by clicking on Add an Attribute, as can be seen in the image below.

Get hands-on with 1400+ tech skills courses.