How to Create Live Search Filter Module in React 18 with Axios

Last Updated on by in React JS

Imagine you are visiting a site and want to obtain the needed information if there is no option or module to search or filter the data.

How embarrassing could it be?

We will try our best to vanish the embarrassment. Therefore we decided to teach you about React live search filter functionality.

The content discovery can be made easy with the Live search filter module. I mean, who does not want to get the desired information quickly?

In this guide, we will help you learn how to create a live search component in React application.

A live search component is always dynamic, and therefore we will use the REST API that mocks the actual data.

To retrieve the records from the server, we need to make HTTP GET request and to make the HTTP request in React we will use the Axios package.

Furthermore, we will use the React Lifecycle methods to create the search filter in React.

Lifecycle methods help us manage the class component’s state and update the data when the data flow or update in the React class component.

Let us start coding react search bar module.

React Axios Build Live Search Component with REST API Example

  • Step 1: Build React Project
  • Step 2: Install Bootstrap Package
  • Step 3: Install Axios Package
  • Step 4: Build Live Search Filter
  • Step 5: Update App Js File
  • Step 6: Run Development Server

Build React Project

To begin with the development, make sure to install node and npm tools on your system.

Type command on your console, hit enter to start the app installing process.

npx create-react-app react-demo

Do not forget to enter into the app directory.

cd live-demo

Install Bootstrap Package

To create the design of search filter module, we will sue the Bootstrap library. It will drastically reduce your CSS writing time.

Go ahead, add the command on the console and press enter.

npm install bootstrap --legacy-peer-deps

Install Axios Package

In order to handle the HTTP requests, we require to add the axios library in our project.

Axios can be installed with just one single command.

npm install axios --legacy-peer-deps

Build Live Search Filter

In your react project folder again create a new folder, name it components/.

Furthermore, create a LiveSearchFilter.js file into the components folder. There after, append all the given code into the file.

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

class LiveSearchFilter extends Component {
  constructor(props) {
    super(props)

    this.state = {
      Profile: [],
    }

    this.cancelToken = ''
    this.getVal = this.getVal.bind(this)
    this.node = React.createRef()
  }

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

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

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

  onChange = async (e) => {
    if (this.cancelToken) {
      this.cancelToken.cancel()
    }

    this.cancelToken = axios.CancelToken.source()

    await axios
      .get('https://jsonplaceholder.typicode.com/users', {
        cancelToken: this.cancelToken.token,
      })
      .then((res) => {
        this.setState({
          Profile: res.data,
        })
      })
      .catch((e) => {
        if (axios.isCancel(e) || e) {
          console.log('Data not found.')
        }
      })

    let stringKwd = e.target.value.toLowerCase()
    let filterData = this.state.Profile.filter((item) => {
      return item.username.toLowerCase().indexOf(stringKwd) !== -1
    })

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

  render() {
    return (
      <>
        <h2>React Search Filter Example</h2>
        <div className="input-group mt-3">
          <input
            type="text"
            className="form-control"
            placeholder="Find ..."
            ref={this.node}
            onClick={this.getVal}
            onChange={this.onChange}
          />
        </div>
        <div className="list-group">
          {this.state.Profile.map((item) => {
            return (
              <a
                className="list-group-item list-group-item-action"
                key={item.id}
              >
                {item.name}
              </a>
            )
          })}
        </div>
      </>
    )
  }
}

export default LiveSearchFilter;

Importing the Axios at the top later will allow us to make the HTTP Get request.

Setting up the state of the component using this.state property, where Profile is the array that holds the users’ data.

Every time a keyword is pressed, the request goes to the server. This really impacts on the performance.

To fix such a problem, use the cancelToken object. It will refrain the additional request from being sent.

We are using the simple array searching and filtering approach.

The filter() method returns the results based on the passed condition. Therefore indexOf() method returns the index of only those results matched with provided values in the Boolean form.

Lastly, we are updating the current state of the live search module and showing the filtered results in the search filter dropdown.

Update App Js File

To show search component on the browser, we have to first register into the App.js file.

import React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css'
import LiveSearchFilter from './components/LiveSearchFilter.js'

function App() {
  return (
    <div className='container mt-3'>
      <LiveSearchFilter />
    </div>
  )
}

export default App;

Run Development Server

The last step is to run the react server, you can invoke the server using the given command.

npm start

Now, you are able to view the app in action on the browser.

http://localhost:3000

Here is the final output:

How to Create Live Search Filter Module in React with Axios

Conclusion

A live search lets users find the expected content through an input field.

In the live search filter, we type in the input box as the keywords match the data present in the server. The filtered results start appearing in the suggestion list.

React lifecycle methods play a vital role in class components and they are almost identical to the Hooks in functional component.

We showed you a productive and dynamic way to implement live search in React using Axios, REST API, and React hooks.