Build React Js Axios Live Search using REST API Tutorial

React Live Search tutorial; In this tutorial, we will teach you how to create a live search in React application. To build the instant search in React js application, we will use the REST API using Axios.

Axios is a Promise-based HTTP client for JavaScript used with Node js and browser. This incredible package helps to make asynchronous JavaScript HTTP requests.

In this profound guide, we will cover essential topics such as how to fetch the data using an API through Axios. How to control the API calls with the help of the Axios cancel token mechanism.

To create the React instant search component, we will not use any third-party package. Instead, we will make the instant search module from scratch.

You will see how to build the custom live search in React. Moreover, we will cover the concepts of React life cycle methods in conjunction with React class component.

How to Create Live or Instant Search in React Js using REST API

  • Step 1: Getting Started
  • Step 2: Create Class Component
  • Step 3: Create Live Search
  • Step 4: Add CSS in Instant Search
  • Step 5: Register LiveSearch Component
  • Step 6: Start Application

Getting Started

Let us commence the first step by creating a new React application, type and execute the given command.

npx create-react-app live-search

Next, enter into the project folder.

cd live-search

Create Class Component

Once you entered into the project, make sure to create the components/ folder, and a LiveSearch.js file.

To create the LiveSearch class use the suggested code.

import React from 'react'

export default function LiveSearch() {
  return (
    <div>
      
    </div>
  )
}

Create Live Search

The Axios get method fetches the result; you may use the JSON placeholder to get the more helpful dummy apis.

As the user starts typing in the input field, the API call is invoked on every typing, which is not good from performance’s perspective.

Axios provides the cancel token paradigm, which accommodates cancel the previous request invoked by the last keyboard hit.

So, head over to components/LiveSearch.js file and append the following code.

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

export default class LiveSearch extends Component {
  constructor(props) {
    super(props)

    this.state = {
      userList: [],
    }

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

  // Detect outside click
  componentDidMount() {
    document.addEventListener('mousedown', this.inputFocus)
  }

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

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

  // Handle livesearch
  onValChange = async (e) => {
    // Check axios token
    if (this.cancelToken) {
      this.cancelToken.cancel()
    }

    // Set axios token
    this.cancelToken = axios.CancelToken.source()

    // Make GET request with token
    await axios
      .get('https://jsonplaceholder.typicode.com/users', {
        cancelToken: this.cancelToken.token,
      })
      .then((res) => {
        this.setState({
          userList: res.data,
        })
      })
      .catch((error) => {
        if (axios.isCancel(error) || error) {
          console.log('Failed to fetch')
        }
      })

    // Filter data
    let searchQuery = e.target.value.toLowerCase()
    let result = this.state.userList.filter((el) => {
      let filterVal = el.name.toLowerCase()
      return filterVal.indexOf(searchQuery) !== -1
    })

    this.setState({
      userList: result,
    })
  }

  render() {
    return (
      <div className="livesearch">
        <input
          onClick={this.inputFocus}
          ref={this.node}
          onChange={this.onValChange}
          type="text"
          placeholder="Search ..."
        />
        {/* {this.state.message} */}
        <ul className="list">
          {this.state.userList.map((item) => {
            return <li key={item.id}>{item.name}</li>
          })}
        </ul>
      </div>
    )
  }
}

Add CSS in Instant Search

Our custom live search component can be designed using the given CSS, open the App.css file and add the provided code.

@charset "UTF-8";
*,
*::before,
*::after {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  list-style: none;
  list-style-type: none;
  text-decoration: none;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
}

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

.livesearch {
  width: 440px;
  font-weight: normal;
  line-height: 1.5;
  color: #252a32;
}

.livesearch input {
  width: 100%;
  padding: 14px 15px;
  border-radius: 4px;
  outline: none;
  background-color: white;
  border: none;
  font-size: 1.2rem;
  border: 1px solid transparent;
  box-shadow: 0 1px 1px rgb(0 0 0 / 0%);
}

.livesearch input:focus {
  border: 1px solid rgb(37, 99, 235);
  box-shadow: 0 1px 1px rgb(0 0 0 / 32%);
}

.livesearch .list {
  max-height: 300px;
  overflow: hidden;
  overflow-y: auto;
  width: 100%;
  margin: 1px 0 0 0;
  padding: 0;
  border-radius: 4px;
  background-color: white;
}

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

.list li:hover {
  background-color: rgb(37, 99, 235);
  color: azure;
  border-color: rgb(37, 99, 235);
}

Register LiveSearch Component

Now, eventually you have to register or add the LiveSearch class into the src/App.js file.

import React from 'react'

import './App.css'
import LiveSearch from './components/LiveSearch'

export default function App() {
  return (
    <div>
      <LiveSearch />
    </div>
  )
}

Start Application

Run the React project using the given command.

npm start

Build React Js Axios Live Search using REST API Tutorial

Summary

In this tutorial, we have learned how to build a live search component in React. Not just that, but we have also covered other topics like how to create the DOM reference to detect the outside click in React class component. The componentDidMount and componentWillUnmount helped us to develop and track the DOM reference.