How To Build Custom Instant Or Live Search In React Js Application
Live Search Module exponentially increases the performance of searching certain content in our web application.
So, we will get to understand in this tutorial how to build a custom instant search feature using Axios HTTP client.
In addition, we will come to know a couple of concepts that are helpful in making instant searches.
The lifecycle methods help in managing the data throughout the component’s various lifecycle.
We will also be learning to use componentDidMount and componentWillUnmount.
We will see 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 very important in live search cases, Generally, a request is made to the server when the user types in the input field.
Moreover, we will see how to detect when users click outside the scope of the live search module. We need this feature to close the dropdown of the live search. We will be creating this feature using createRef() method.
React Js Custom Live Or Instant Search Example
Step 1- Create New React Project
Step 2- Create Live Search Component
Step 3- Style Module With CSS
Step 4- Import Component In App Js
Step 5- Run React App
Let’s learn in detail now:
Step 1-Create New React Project
Hope that you have already followed the first step i.e simply to download or install new React app using the following command:
npx create-react-app react-project
After we have created the new React app, we need to enter into the app:
cd react-project
Step 2- Create Live Search Component
Here, in this step, we will create the components directory. Then, we would make the InstantSearch.js file. Afterward, we require to add the following code into the components/InstantSearch.js file to build the component:
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
Step 3- Style Module With CSS
We will have to create everything from scratch. So, we will be using the below CSS code to style the instant search module.
Further, we get into the index.css and append the below 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);
}
Step 4- Import Component In App Js
After we have imported the search module into the main component, we head over to the App.js primary component and insert the below code:
import React from 'react'
import InstantSearch from './components/InstantSearch'
function App() {
return (
<div>
<InstantSearch />
</div>
)
}
export default App
Step 5- Run React App
Since we have to see the final output, we go into the command-line tool for executing the given command:
npm start
Conclusion
So, we have learned in this guide to create a live/instant search component in React.
Thanks