How to Build Custom Instant or Live Search in React Js

Last updated on: by Digamber

Live search module exponentially increases the performance of searching certain content in your web application.

In this tutorial, you will learn how to create a live search in React js app without using any package.

You will be taught how to build a custom instant search feature using Axios HTTP client.

Apart from that, you will also learn a couple of concepts helpful in making instant searches and also help you in your development journey.

The lifecycle methods are the core concepts of React; they really help manage the data throughout the components’ various lifecycle.

We will enlighten you about a couple of lifecycle methods, and you will learn to use componentDidMount and componentWillUnmount.

We will show you how to use a request token to make the HTTP get a request in React related to the Axios library. The cancel token paradigm is significant in live search cases; typically, a request is made to the server as the user types in the input field.

Imagine if the request is invoked on every keyword is typed, it may severely impact the performance. Luckily, you can control it by using the cancel token strategy.

Moreover, you will also be taught how to detect when users click outside the scope of the live search module. This feature is required to close the dropdown of the live search; we will create the feature using the createRef() method.

Let’s get started …

React Js Custom Live or Instant Search Example

  • Step 1: Create React Project
  • Step 2: Create Live Search Component
  • Step 3: Style Module with CSS
  • Step 4: Import Component in App Js
  • Step 5: Run + Test App

Create React Project

We assume you already have the app ready, however if not then go ahead and use the given command to set up the new app.

We named react-project to our app, you may name it anything you want.

npx create-react-app react-project

Right after the blank app is created, dont forget to enter into the app.

cd react-project

Create Live Search Component

There are a couple of things that you need to take care of before you move further.

First, create the components directory, then make the InstantSearch.js file.

In the following file, we will write the code to build the component.

Add code into the 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

Style Module with CSS

Since we are building the custom functionality, we have to create everything from scratch; therefore, we will use the given CSS code example to style the instant search module.

Get into the index.css, and make sure to append the following code within the file.

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);
}

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

Run + Test App

You must be excited to see the final output, well don’t wait go to the command line tool and execute the provided command.

npm start

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

How to Build Custom Instant or Live Search in React Js

Conclusion

Throughout this profound guide, we have gone through every topic that is needed for a beginner developer to create a live/instant search component in React.

I reckon this guide will help all beginners looking to create an instant search in React.

Digamber

I am Digamber, a full-stack developer and fitness enthusiast. I crafted this site to bestow my coding experience and love to write on JavaScript, React, Angular, Vue, Laravel.