React 18 Build Custom Search / List Filter Component Tutorial

Last Updated on by in React JS

Search filter amplifies the user experience; it helps site visitors to refine the search with a particular keyword.

Be it product page, video content or any other significant information. With the search filter component, you always have the option to narrow down your search results.

In this tutorial, you will discover how to create search filter functionality in React’s class component.

We will also demonstrate how to use Axios with free public API to fetch the data into the React search filter component.

To develop the list search filter in React, you will also be using the Bootstrap CSS framework. With the help of this profound UI design library, we will create the subtle filter list bar.

React lifecycle methods are handy when it comes to managing the lifecycle of the class component.

This post will try its best to show how to use mounting and unmounting for the filter search module.

How to Create Search List Filter in React with Public API

  • Step 1: Build React Application
  • Step 4: Configure Bootstrap in React
  • Step 3: Build React Search Filter File
  • Step 5: Register Search Filter in React
  • Step 6: Start React Server

Build React Application

We are sure already have set up a React project. However, if not go ahead and use the given command to commence the app downloading process.

npx create-react-app react-world

Now, straight enter into the app folder.

cd react-world

Configure Bootstrap in React

Subsequently, type the following command and begin bootstrap package installing in React.

npm install bootstrap --legacy-peer-deps

Head over to App.js file, in this file you have to set the bootstrap CSS path.

import 'bootstrap/dist/css/bootstrap.min.css'

Build React Search Filter File

Now, we will build a separate component in our React app. Take a step, and put it in components/ directory, after you get into the folder, create FilterSearch.js file.

Afterwards, put given code in the FilterSearch.js file.

import React, { Component } from 'react'
import axios from 'axios'

class DynamicSearch extends Component {
  constructor(props) {
    super(props)
    this.state = {
      Student: [],
    }
    this.node = React.createRef()
  }

  componentDidMount() {
    document.addEventListener('mousedown', this.onSearchClick)
  }

  componentWillUnmount() {
    document.removeEventListener('mousedown', this.onSearchClick)
  }

  onSearchClick = (e) => {
    if (this.node.current.contains(e.target)) {
      return
    }
    this.setState({
      Student: [],
    })
  }

  handleAPI = async (e) => {
    await axios
      .get('https://jsonplaceholder.typicode.com/users')
      .then((res) => {
        this.setState({
          Student: res.data,
        })
      })
      .catch((err) => {
        alert(err)
      })

    let convertToLc = e.target.value.toLowerCase()

    let filterData = this.state.Student.filter((e) => {
      let nameToLc = e.name.toLowerCase()
      return nameToLc.indexOf(convertToLc) !== -1
    })

    this.setState({
      Student: filterData,
    })
  }

  render() {
    return (
      <div className="container mt-5">
        <h2>React Filter Search Module Example</h2>

        <div className="mt-4">
          <input
            type="text"
            onClick={this.onSearchClick}
            className="form-control"
            onChange={this.handleAPI}
            placeholder="Search ..."
            ref={this.node}
          />
        </div>
        <ul className="list-group">
          {this.state.Student.map((res) => {
            return (
              <a
                href="#"
                className="list-group-item list-group-item-action"
                key={res.id}
              >
                {res.name}
              </a>
            )
          })}
        </ul>
      </div>
    )
  }
}

export default DynamicSearch;

Register Search Filter in React

Now, all the major work is done, next open the App.js file.

Here within this file, you have to import the component where you wrote the filter search code.

import React from 'react'

import DynamicSearch from './components/DynamicSearch'
import 'bootstrap/dist/css/bootstrap.min.css';


export default function App() {
  return (
    <div className="App">
      <DynamicSearch />
    </div>
  )
}

Start React Server

We have eventually reached to the last step, and we are going to start the react server.

Run the given command from the terminal.

npm start

You can test the filter search through the given url.

http://localhost:3000

React Js Build Custom Dynamic Search Filter Tutorial

Conclusion

We have created the react filter search; however, we discussed multiple topics like using Axios to make an HTTP request, lifecycle methods to handle data coming from an API and react events.

At the end of this article, we successfully built a dynamic search filter that helps us refine search results based on a specific keyword.