LWC Search Component Example: How to Build a Search Functionality in Lightning Web Components

Search components are essential for improving user experiences by enabling quick access to specific records or data in Salesforce. This guide provides a step-by-step example to create a Lightning Web Component (LWC) Search Component that dynamically fetches and displays search results based on user input.


Features of the Search Component

  • Dynamic search with real-time updates.
  • Fetch records using Apex.
  • Display results in a list with clickable items.

Step-by-Step Implementation

1. Create the Apex Controller

To fetch data, create an Apex class that handles SOQL queries based on the search term.

Apex Class: SearchController

public with sharing class SearchController {
    @AuraEnabled
    public static List<Account> searchAccounts(String searchTerm) {
        // Add wildcards for partial matching
        String searchKey = '%' + searchTerm + '%';
        return [SELECT Id, Name FROM Account WHERE Name LIKE :searchKey LIMIT 10];
    }
}

2. Create the LWC Component

Run the following command to create a new LWC component:

sfdx force:lightning:component:create --name SearchComponent

3. Develop the LWC Files

searchComponent.html

This file contains the input field and the list to display search results.

<template>
    <div class="search-container">
        <lightning-input
            type="text"
            label="Search Accounts"
            placeholder="Enter account name"
            onchange={handleSearchInput}>
        </lightning-input>
        
        <template if:true={accounts}>
            <ul class="search-results">
                <template for:each={accounts} for:item="account">
                    <li key={account.Id} onclick={handleAccountClick}>
                        {account.Name}
                    </li>
                </template>
            </ul>
        </template>

        <template if:true={error}>
            <p class="error-message">Error: {error}</p>
        </template>
    </div>
</template>

searchComponent.js

This file contains the logic to handle user input, fetch data, and display results.

import { LightningElement, track } from 'lwc';
import searchAccounts from '@salesforce/apex/SearchController.searchAccounts';

export default class SearchComponent extends LightningElement {
    @track accounts = [];
    @track error;

    handleSearchInput(event) {
        const searchTerm = event.target.value;

        // Call Apex only if the input is not empty
        if (searchTerm.length >= 2) {
            searchAccounts({ searchTerm })
                .then((result) => {
                    this.accounts = result;
                    this.error = undefined;
                })
                .catch((error) => {
                    this.error = error.body.message;
                    this.accounts = [];
                });
        } else {
            this.accounts = [];
            this.error = undefined;
        }
    }

    handleAccountClick(event) {
        // Retrieve the clicked account's name
        const selectedAccount = event.target.textContent;
        console.log('Selected Account:', selectedAccount);
    }
}

searchComponent.js-meta.xml

Configure the component for use in Lightning App Builder or other supported environments.

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>57.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

4. Deploy the Component

Deploy the component to your Salesforce org:

sfdx force:source:deploy --sourcepath force-app/main/default/lwc/searchComponent

5. Add the Component to a Lightning Page

  1. Navigate to App Builder.
  2. Add the SearchComponent to a page (e.g., Home, App, or Record Page).
  3. Save and activate the page.

Key Features of the Example

  1. Dynamic Search:
    • The onchange event fetches results in real time as the user types.
  2. Error Handling:
    • Displays an error message if the Apex method fails or the search term is invalid.
  3. Responsive Design:
    • Adapts to various screen sizes using Lightning Web Component styling.

Best Practices for LWC Search Components

  1. Optimize Apex Queries:
    • Use selective fields and limits to prevent performance issues.
  2. Debounce Input:
    • Avoid multiple Apex calls by implementing a debounce mechanism for the search input.

Debounce Example:

handleSearchInput(event) {
    const searchTerm = event.target.value;
    clearTimeout(this.delayTimeout);
    this.delayTimeout = setTimeout(() => {
        this.fetchAccounts(searchTerm);
    }, 300);
}
  1. Pagination for Large Results:
    • Implement pagination or infinite scrolling for large datasets.
  2. Security:
    • Use with sharing in Apex classes to respect Salesforce security settings.

Conclusion

Building a search component in LWC is straightforward with the use of lightning-input and Apex for data fetching. By following the example provided, you can create a dynamic, user-friendly search functionality tailored to your business needs. Implementing best practices like input debouncing and efficient Apex queries ensures a seamless user experience while maintaining performance.