Building React 18 Custom Live Search with Axios

Last Updated on by in React JS

How to Build Custom Instant or Live Search in React Js

Live search, or instant search, stands as an indispensable functionality for web developers, pivotal in enabling users to dynamically conduct searches via an input field across a wide range of records.

If you’re seeking insights on how to create a custom live search functionality in React using the Axios package, you are at good place.

Axios is a JavaScript library that provides a simple way to handle HTTP requests in JavaScript-based frameworks. We’ll use it to send HTTP requests to server, retrieve the data from the server, and incorporate and display data via the live search component.

We will process the data and display filtered results on the live search module as soon as users begin typing in an input control.

React Axios Custom Live Search Example

To create a custom live search in React 18, you can follow these general steps:

Step 1: Set Up Your React Environment

Ensure you have React 18 installed and set up in your development environment.

npx create-react-app react-project

Right after the blank app is created, don’t forget to enter into the app.

cd react-project

Step 2: Create a React Component for Live Search

Create a new component (let’s call it InstantSearch.js) that will handle the live search functionality.

Insert code in components/InstantSearch.js file.

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

class InstantSearch extends Component {
  constructor(props) {
    super(props)
    this.state = {
      Posts: [],
    }

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

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

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

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

  onLsChange = async (e) => {
    if (this.isReqToken) {
      this.isReqToken.cancel()
    }

    this.isReqToken = axios.CancelToken.source()

    await axios
      .get('https://jsonplaceholder.typicode.com/albums', {
        isReqToken: this.isReqToken.token,
      })
      .then((res) => {
        this.setState({
          Posts: res.data,
        })
      })
      .catch((error) => {
        if (axios.isCancel(error) || error) {
          console.log('Could not get')
        }
      })

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

    let searchRes = this.state.Posts.filter((e) => {
      let finalRes = e.title.toLowerCase()
      return finalRes.indexOf(filterSearch) !== -1
    })

    this.setState({
      Posts: searchRes,
    })
  }

  render() {
    return (
      <div className="searchModule">
        <h2> React Live Search Example - positronX</h2>
        <input
          onClick={this.onIptClick}
          onChange={this.onLsChange}
          type="text"
          placeholder="Search ..."
          ref={this.node}
        />
        <ul>
          {this.state.Posts.map((res) => {
            return <li key={res.id}>{res.title}</li>
          })}
        </ul>
      </div>
    )
  }
}

export default InstantSearch

Inside the InstantSearch component, create state variables to store the search query and the filtered search results.

Step 3: Style and Customize

Style the live search component based on your design preferences, and make sure it integrates seamlessly into your UI component.

Update code: index.css

body {
  display: flex;
  justify-content: center;
  font-family: sans-serif;
  background: #f0eff2;
  padding-top: 40px;
}

ul, ol {
  list-style: none;
  margin: 0;
  padding: 0;
}

.searchModule {
  width: 500px;
  color: #252a32;
  overflow: hidden;
}

.searchModule input {
  padding: 15px;
  border-radius: 3px;
  outline: none;
  border: none;
  width: 100%;
  font-size: 1.3rem;
  border: 1px solid transparent;
  background-color: #ffffff;
}

.searchModule input:focus {
  border: 1px solid rgb(47, 110, 245);
}

.searchModule ul {
  padding: 0;
  overflow: hidden;
  overflow-y: auto;
  width: 100%;
  margin-top: 1px;
  border-radius: 3px;
  max-height: 310px;
  background-color: #ffffff;
}

.searchModule ul li {
  padding: 15px;
  background: white;
  border-bottom: 1px solid #c7c0c0;
  margin-top: 0.5px;
}

.searchModule li:hover {
  color: rgb(241, 249, 249);
  border-color: rgb(47, 110, 245);
  background-color: rgb(47, 110, 245);
}

Step 4: Import Component in App Js

Now, we will import the search module in the main component.

Hence, head over to the App.js primary component and insert the following code as suggested.

import React from 'react'

import InstantSearch from './components/InstantSearch'

function App() {
  return (
    <div>
      <InstantSearch />
    </div>
  )
}

export default App

Step 5: Run + Test App

Test the live search functionality thoroughly to ensure it works as expected.

npm start

The above command run the react app and automatically manifest what we have created so far.

Conclusion

You may create aesthetically beautiful, seamless functionality that enables users to dynamically search, filter, and receive the desired search results in a matter of seconds by properly implementing live search in React.

With the help of this tutorial, developers will be able to easily improve user experiences by building bespoke React fast search capabilities.