Building a Filterable List Component in React JS

Building a Filterable List Component in React JS is a common task for many web developers. The ability to filter a list of items based on user input is a powerful feature that can greatly enhance the user experience of your application.

In this tutorial, we will be building a filterable list component in React JS that will take in sample object data as a prop and allow the user to filter the data based on a search query. We will be using the useState hook to manage the component’s state and a filter function to filter the data.

We will start by creating a new React project using the create-react-app command and then proceed to create the filterable list component in its own file. We will then define the component’s initial state and create a filter function that will filter the data based on the search query. Next, we will render the filtered data by mapping over the filtered data and returning JSX for each item in the array.

We will then add an input field and a button that will allow the user to update the search query. We will use the onChange event to update the search query state and the onClick event to call the filter function. After this, we will add a stylesheet to the project and use CSS to style the component.

Let’s start implementation…

 

Step 1: Create a new React project

Before we begin building our filterable list component, we need to create a new React project. You can do this by running the following command in your terminal:

npx create-react-app my-app

This will create a new directory called “my-app” that contains all the necessary files for a basic React application.

 

Step 2: Create the FilterableList component

In your project’s root directory, create a new file called “FilterableList.js” and import React and the useState hook.

import React, { useState } from 'react';

 

Step 3: Define the component’s initial state

In your FilterableList component, define an initial state for your data and a search query. You can use the useState hook to do this.

const FilterableList = (props) => {
  const [data, setData] = useState(props.data);
  const [searchQuery, setSearchQuery] = useState('');

 

Step 4: Create a filter function

Define a function that will filter your data based on the search query. This function should return a new array of filtered data.

const filterData = (query) => {
  return data.filter((item) => {
    return item.name.toLowerCase().includes(query.toLowerCase());
  });
}

 

Step 5: Render the filtered data

Render your data by mapping over the filtered data and returning JSX for each item in the array.

return (
  <div>
    {filterData(searchQuery).map((item) => {
      return <div key={item.id}>{item.name}</div>
    })}
  </div>
);

 

Step 6: Add a search input and button

Add an input field and a button that will allow the user to update the search query. You can use the onChange event to update the search query state and the onClick event to call the filter function.0

return (
  <div>
    <input
      type='text'
      value={searchQuery}
      onChange={(e) => setSearchQuery(e.target.value)}
    />
    <button onClick={() => setData(filterData(searchQuery))}>
      Search
    </button>
    {filterData(searchQuery).map((item) => {
      return <div key={item.id}>{item.name}</div>
    })}
  </div>
);

 

Step 7: Add styles

In order to style your component, you will need to add a stylesheet to your project. You can create a new file called “FilterableList.css” in the same directory as your “FilterableList.js” file and add the following CSS styles to it:

input {
  padding: 12px 20px;
  margin: 8px 0;
  box-sizing: border-box;
  border: 2px solid #ccc;
  border-radius: 4px;
}

button {
  background-color: #4CAF50;
  color: white;
  padding: 14px 20px;
  margin: 8px 0;
  border: none;
  cursor: pointer;
  border-radius: 4px;
}

div {
  padding: 12px 20px;
  margin: 8px 0;
  box-sizing: border-box;
  border: 2px solid #ccc;
  border-radius: 4px;
}

To use this stylesheet in your component, you will need to import it at the top of your “FilterableList.js” file:

import './FilterableList.css';

You can then add the className to the elements you want to style, for example:

return (
    <div className="FilterableList">
      <input className="search-input"
        type='text'
        value={searchQuery}
        onChange={(e) => setSearchQuery(e.target.value)}
      />
      <button className="search-btn" onClick={() => setData(filterData(searchQuery))}>
        Search
      </button>
      {filterData(searchQuery).map((item) => {
        return <div className="list-item" key={item.id}>{item.name}</div>
      })}
    </div>
  );

This way you can customize the component according to your design requirement.

Note: If you’re using create-react-app, there’s no need to configure anything to use CSS. You can create a CSS file in the src folder, import it in the component and use the class names as mentioned above

 

Step 8: Test the component

Test your component by passing in sample object data as a prop and ensuring that the filtering is working correctly.

const sampleData = [
  { id: 1, name: 'John Doe' },
  { id: 2, name: 'Jane Smith' },
  { id: 3, name: 'Bob Jones' }
];

function App() {
  return (
    <div className="App">
      <FilterableList data={sampleData} />
    </div>
  );
}

 

You can now run your application using the command npm start in the root folder of your project and you should see the filtered list component running on the page.

 

Here is the full component file code:

import React, { useState } from 'react';

const FilterableList = (props) => {
  const [data, setData] = useState(props.data);
  const [searchQuery, setSearchQuery] = useState('');

  const filterData = (query) => {
    return data.filter((item) => {
      return item.name.toLowerCase().includes(query.toLowerCase());
    });
  }

  return (
    <div>
      <input
        type='text'
        value={searchQuery}
        onChange={(e) => setSearchQuery(e.target.value)}
      />
      <button onClick={() => setData(filterData(searchQuery))}>
        Search
      </button>
      {filterData(searchQuery).map((item) => {
        return <div key={item.id}>{item.name}</div>
      })}
    </div>
  );
}

export default FilterableList;

 

Other uses

The filterable list component can be used in a variety of applications such as displaying a list of products, searching through a list of users, or even displaying a list of articles. You can also pass different data as props to the component and filter it accordingly.

 

Conclusion

In this tutorial, we walked through the process of building a filterable list component in React JS. We used the useState hook to manage the component’s state and a filter function to filter the data based on the search query. We also added an input field and a button to allow the user to update the search query and a stylesheet to style the component. With this component, you will be able to pass in sample object data and filter it based on the search query, which can be very useful in a variety of applications.

Leave a Comment

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

Scroll to Top