React Tutorial- Build Custom Search/List Filter Component

Build Custom Search/List Filter Component In React

First of all, we should understand that a search filter amplifies the user experience by helping the site visitors to refine the search with a keyword. It can be used anywhere from a product page to video content to any other information. We can easily narrow down the search results by using the search filter component.

 

In this tutorial, we are going to learn how to create search filter functionality and would also see the demonstration to use Axios with free public API to fetch the data into the React search filter component.

For developing this list search filter in React, we 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. We will also get to know 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 App

Step 2- Configure Bootstrap In React

Step 3- Build React Search Filter File

Step 4- Register Search Filter In React

Step 5- Start React Server

 

Let’s learn in detail now:

Step 1- Build React App

The very first step in implementing the above-mentioned is to set up a new React project. We have to use the given command in order to complete the downloading process:

npx create-react-app react-world

Afterward, we will enter into the app folder:

cd react-world

 

Step 2- Configure Bootstrap In React

In the second step, we simply have to type the following command and start the bootstrap package installing in React:

npm install bootstrap

Further is to head over to the App.js file. In this file, we will have to set the bootstrap CSS path:

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

 

Step 3- Build React Search Filter File

Here, we need to build a separate component in our React app. Then, we will put it in components/ directory. After getting into the folder, we create FilterSearch.js file.

Afterward, we will put the following code into 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;

 

Step 4- Register Search Filter In React

By now, we are just done with most of the work. After this, we have to open App.js file. Here within this file, we have to import the component where we 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>
  )
}

 

Step 5- Start React Server

Since this is the last step of this tutorial, we have to start the server now.

We will run the given command from the terminal:

npm start

 

Conclusion

So friends, hope that you have easily understood this guide for using Axios to make an HTTP request, lifecycle methods to handle data coming from an API and React events.

We have successfully built a dynamic search filter that helps us refine search results based on a specific keyword.

 

Thanks

Leave a Reply

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