React Filter List Example – Search Filter Dynamic List Items

In this react tutorial, you will learn how to populate a dynamic list of items from a remote server then filter the items based on user input. The search filter input box will take the user text terms to filter the dynamic list items for single or multiple properties on each object item.

The React filter list with a search box on top to filter the list of object items. We will fetch the dynamic object from a remote server and traverse the list using the map function. The list will be populated in the JSX template and the user will be able to select a single item to show it by setting its own state.

To filter the list item in the object, we will use the Javascript filter method. Also, we will maintain three state variables in the FilterList function component. let’s get into the demonstration application with an example showing how to create a filter list with a search box on top of it and show selected value.

Adding Filter List in React JS Application

  • Step 1 – Create React App
  • Step 2 – Install Bootstrap Library
  • Step 3 – Setup FilterList Function Component
  • Step 4 – Adding Filter List in App.js
  • Step 5 – Run React Application

 

Step 1 – Create React App

First, create a new react js application to keep the demonstration simple and handy. Execute the following command to download a new React project at your local:

npx create-react-app react-filterlist-app

Move inside the app folder

cd react-filterlist-app

Step 2 – Install Bootstrap Library

To quickly style the app, we will import the bootstrap.min.css file. Install the package by executing the following npm command in the terminal:

npm install bootstrap --save

Step 3 – Setup FilterList Function Component

Now, head towards the src/components folder and create a new file named FilterList.js to keep our function component. Open the src/components/FilterList.js file and update it as shown below:

import React from "react";
import { useEffect, useState } from "react";

let MY_LIST = [];

function FilterList() {
  const [search, setSearch] = useState("");
  const [selected, setSelected] = useState({});
  const [filterlist, setFilterlist] = useState(MY_LIST);

  function onKeyUpHandler(e) {
    setSearch(e.target.value.toLowerCase());
  }

  function onSelectItem(e, item) {
    setSelected(item);
    setSearch("");
    clearFilter();
  }

  function clearFilter() {
    document.getElementById("searchFilter").value = "";
  }

  function fetchData() {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
        MY_LIST = data;
      });
  }

  useEffect(() => {
    console.log("useEffect");
    fetchData();
  }, [""]);

  useEffect(() => {
    const filteredList = MY_LIST.filter((item) => {
      let all_str = `${item.id} ${item.title}`.toLowerCase();
      //return all_str.indexOf(search) > -1; // View All When Search Empty
      return all_str.indexOf(search) > -1 && search;
    });
    setFilterlist(filteredList);
  }, [search]);

  return (
    <div>
      <div className="mb-3">
        <h1>Filter List Example - FreakyJolly.com</h1>
        <label className="form-label">Filter List</label>
        <input
          id="searchFilter"
          type="text"
          className="form-control"
          defaultValue={search}
          placeholder="Enter ID or Name"
          onKeyUp={onKeyUpHandler}
        />
      </div>
      <div>
        <h6>
          Selected Item : {selected.id}) {selected.title}
        </h6>
      </div>
      <ul className="list-group">
        {filterlist.map((item, key) => (
          <li
            className="list-group-item"
            key={key}
            value={item.id}
            onClick={(e) => onSelectItem(e, item)}
          >
            {item.id}) {item.title}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default FilterList;

The function component FilterList is having three state variables search, selected and filterList with their respective setters.

The useEffect hooks are used to call the fetch method at component initialization and when the search state is updated to filter the list.

The onKeyUpHandler and onSelectItem functions are taking care of keyup events on the input search box and list item selection.

Step 4 – Adding Filter List in App.js

Next, import the FilterList component into the App.js file as shown below:

import React from "react";
import "./App.css";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import FilterList from "./components/filterlist";

function App() {
  return (
    <div className="container mt-5">
      <FilterList />
    </div>
  );
}

export default App;

Step 5 – Run React Application

Finally, run the react js app to see the filter list feature in action. Execute the following command in the terminal window:

npm start

It will start the development web server and open the react app in eh browser window at the following URL:

http://localhost:3000

Leave a Comment

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