React : Filter List Component with Text Highlighting | react-highlight-words

In this tutorial, we will learn how to create a React filter list component with matching text highlighting, and also pass the selected item value to the parent component. This feature allows users to quickly find and identify the information they are looking for within a large data set.

We will use a sample JSON object as the data source for our filter list and walk through each step of the process, including setting up the component, creating the filter function, implementing the highlighting feature and passing the selected item value to the parent component.

To achieve this feature we will be using the react-highlight-words library.

 

Step 1: Install the react-highlight-words Plugin

Execute the following command in your react app to install the package react-highlight-words

npm i react-highlight-words

The react-highlight-words is a library for React that allows you to easily highlight words or phrases in a block of text. It provides a simple and flexible way to highlight matching text in a searchable list or other text-based content without using the dangerouslySetInnerHTML property.

The library provides a Highlight component that can be used to wrap any text or string that you want to highlight. By passing an array of search words, it will automatically highlight all the occurrences of the matching words or phrases in the text. The library also provides various options to customize the highlight style, text to highlight and many more.

 

Step 2: Set up the filter component

Create a new component called FilterList and import the sample JSON object. In the render method, add an input field for the filter text and a list to display the data.

In the component’s class, create a function called handleChange that filters the data based on the value of the filter text input.

import React, { Component } from "react";
import data from "./data.json";
import Highlight from "react-highlight-words";

class FilterList extends Component {
  state = {
    filterText: "",
    filteredData: data.data,
    selectedItem: null,
  };

  handleChange = (event) => {
    const filteredData = data.data.filter((item) => {
      return (
        item.name.toLowerCase().includes(event.target.value.toLowerCase()) ||
        item.email.toLowerCase().includes(event.target.value.toLowerCase()) ||
        item.phone.includes(event.target.value)
      );
    });
    this.setState({ filterText: event.target.value, filteredData });
  };

  handleSelect = (item) => {
    this.setState({ selectedItem: item });
    this.props.onSelect(item);
  };

  render() {
    const { filterText, filteredData } = this.state;
    return (
      <>
        <input
          value={filterText}
          onChange={this.handleChange}
          placeholder="Search..."
        />
        <ul>
          {filteredData.map((item) => (
            <li key={item.id} onClick={() => this.handleSelect(item)}>
              <Highlight
                searchWords={[filterText]}
                autoEscape={true}
                textToHighlight={item.name}
              />{" "}
              -{" "}
              <Highlight
                searchWords={[filterText]}
                autoEscape={true}
                textToHighlight={item.email}
              />{" "}
              -{" "}
              <Highlight
                searchWords={[filterText]}
                autoEscape={true}
                textToHighlight={item.phone}
              />
            </li>
          ))}
        </ul>
      </>
    );
  }
}

export default FilterList;

The above component called FilterList that will handle the state of the search input, the filtered data, and the selected item. The component will have an input element and a list element that will be populated with the filtered data. The handleChange method will be used to filter the data and set the state based on the search input. The handleSelect method will be used to handle the click event on the list items, which will set the selected item in the state and pass it to the parent component.

In our class component we have three state elements, one for filterText which is used for storing the search text, filteredData to store the filtered data on the basis of search text and selectedItem to store the selected item from the list. We have two methods handleChange and handleSelect which are used for filtering the data and setting the selected item respectively. The render method is used to render the input element and the list of filtered data with highlighted matching text.

 

Step 2: Use FilterList in App Component

The following code will show, how you can pass the selected item value from the FilterList component to the App component:
import React, { Component } from "react";
import FilterList from "./FilterList";

class App extends Component {
  state = {
    selectedItem: null,
  };

  handleSelectedItem = (item) => {
    this.setState({ selectedItem: item });
  };

  render() {
    return (
      <div className="App">
        <FilterList onSelect={this.handleSelectedItem} />
        {this.state.selectedItem && (
          <div>
            <h2>Selected Item:</h2>
            <p>Name: {this.state.selectedItem.name}</p>
            <p>Email: {this.state.selectedItem.email}</p>
            <p>Phone: {this.state.selectedItem.phone}</p>
          </div>
        )}
      </div>
    );
  }
}

export default App;

 

Step 3: Create Data File

In the src folder create a data.json file with sample data for filter:

{
  "data": [
    {
      "id": 1,
      "name": "John Smith",
      "email": "[email protected]",
      "phone": "555-555-5555"
    },
    {
      "id": 2,
      "name": "Jane Doe",
      "email": "[email protected]",
      "phone": "555-555-5556"
    },
    {
      "id": 3,
      "name": "Bob Johnson",
      "email": "[email protected]",
      "phone": "555-555-5557"
    }
  ]
}

 

Conclusion

In conclusion, we have learned how to build a filter list component in React that highlights the matching text as the user types in a search input. We used the react-highlight-words library to achieve this feature without using the dangerouslySetInnerHTML property, which is not recommended for security reasons. We have implemented a simple class component called FilterList that handles the state of the search input, the filtered data, and the selected item.

The component has an input element and a list element that is populated with the filtered data. The handleChange method is used to filter the data and set the state based on the search input, and the handleSelect method is used to handle the click event on the list items. The render method is used to render the input element and the list of filtered data with highlighted matching text.

We also learned how to use the react-highlight-words library and how it can be used to easily highlight words or phrases in a block of text. We also discussed how to customize the highlight style and many more options provided by the library. By following the steps outlined in this tutorial, you should now have a better understanding of how to build a filter list component with matching text highlight in React.

Leave a Comment

Your email address will not be published. Required fields are marked *