Search Filter in React JS Creating a Dynamic Search List Component

Search Filter in React JS: Creating a Dynamic Search List Component

Learn how to create a dynamic search list component in React JS that allows users to filter and search through a list of items. Discover how to implement filtering functionality and improve user experience with a responsive and efficient search feature.

Search Filter in React JS

Introduction

This tutorial explores building a dynamic Search Filter in React JS. This component will enable users to search and filter through a list of items, making it easier to find specific content. We’ll leverage React’s useState hook to manage the search term and filter the list accordingly. By the end of this article, you’ll have a functional search list component that can be integrated into various React applications.

Understanding the SearchList Component

Before we dive into the implementation, let’s understand the structure and functionality of the SearchList component.

import React, { useState } from 'react';
 
const SearchList = ({ itemList }) => {
  const [searchTerm, setSearchTerm] = useState('');
  
  const handleSearch = (event) => {
    setSearchTerm(event.target.value);
  };
  
  const filteredList = itemList.filter((item) =>
    item.toLowerCase().includes(searchTerm.toLowerCase())
  );
  
  return (
    <div className='flex flex-col items-center justify-center p-4'>
      <input
      className='px-4 py-2 border border-gray-400 rounded-md focus:outline-none focus:ring focus:border-blue-300'
        type="text"
        placeholder="Search..."
        value={searchTerm}
        onChange={handleSearch}
      />
      <ul className='mt-4'>
        {filteredList.map((item, index) => (
          <li className='py-2 border-b border-gray-300' key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
};
 
export default SearchList;

The SearchList component receives an array of itemList as a prop. It initializes a state variable searchTerm using the useState hook to store the user’s input for filtering. The handleSearch function updates the state with the current search term as the user types in the input field.

The component then filters the itemList based on the searchTerm using the filter method. It converts both the search term and each item to lowercase to perform a case-insensitive search.

Finally, the filtered list is rendered as an unordered list (

) with each item displayed as a list item (* ).

Also Read: Creating the edit profile, add (opens in a new tab) links (opens in a new tab) Page | LinkTree Project (opens in a new tab)

Implementing the SearchList Component

To create the SearchList component, follow these steps:

Step 1: Set Up a New React Project

If you haven’t already set up a React project, create one using create-react-app:

npx create-react-app my-search-list-app 
cd my-search-list-app

Step 2: Create the SearchList Component

Inside the src folder, create a new file named SearchList.js, and paste the SearchList component code into it.

Step 3: Use the SearchList Component

Now, let’s use the SearchList component in the main application file (App.js).

import { useState } from 'react'
import SearchList from './Components/SearList'
 
 
 
function App() {
  const itemList = [
    'Apple',
    'Banana',
    'Orange',
    'Grapes',
    'Mango',
    'Pineapple',
    'Watermelon',
  ];
  
 
  return (
   
  <div>
    <SearchList products ={itemList }/>
  </div>
   
  )
}
 
export default App;

Here, we’ve defined an itemList array with some fruit names. The SearchList component is then used, passing the itemList array as a prop.

Styling the SearchList Component

For a better user experience, we can apply some basic styling to the SearchList component. Let’s use Tailwind CSS to style the component.

Step 1: Install Tailwind CSS

Install Tailwind CSS and its dependencies using npm:

npm install tailwindcss postcss autoprefixer

Step 2: Create Tailwind CSS Configuration

In the root directory of your project, create a tailwind.config.js file:

module.exports = {
  purge: [],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
};

Step 3: Import Tailwind CSS in index.css

In the src folder, create a new file named index.css:

@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';

Step 4: Import index.css in index.js

Open the index.js file in the src folder and import the index.css file:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
 
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
 
reportWebVitals();

Step 5: Add Custom Styling to SearchList.js

With these steps, your SearchList component will be styled using Tailwind CSS, providing a clean and modern look to the search list interface.

Conclusion

In this tutorial, we’ve successfully created a dynamic search list component in React JS. By leveraging the useState hook, we enabled users to filter through a list of items in real-time. Additionally, we enhanced the user experience by applying Tailwind CSS for simple yet elegant styling. You can further extend this component to accommodate more complex filtering requirements and seamlessly integrate it into various React applications.

Now, you’re equipped with a valuable tool to empower your users with efficient and responsive search functionality in your React projects.

IndGeek provides solutions in the software field, and is a hub for ultimate Tech Knowledge.