How To Create Live Search Filter Module In React With Axios
Everyone understands quite well how significant it is for a site to have an option or module to search or filter the data.
So, in this tutorial, we will learn about React Live Search Filter functionality. In order to make it easy for the user to get the desired information, we need to use the Live Search Filter module. We will have to use the REST API for creating a live search component in React app.
As we have to retrieve the data from the server, therefore we need to make HTTP GET request and to make the HTTP request in React, we would be using the Axios package.
We will also be using 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 updates in the React Class component.
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
Let’s learn in detail now:
Step 1- Build React Project
The first step towards creating and implementing the above-mentioned, firstly, we need to install node as well as npm tools on our system.
For this, we have to type the following command on our console, hit enter to start the app installing process:
npx create-react-app react-demo
Further, we would move into the app directory:
cd live-demo
Step 2- Install Bootstrap Package
Here, we will install or download the Bootstrap library in order to create the design of the search filter module.
Afterward, we have to add the command on the console and hit enter:
npm install bootstrap
Step 3- Install Axios Package
In this step, we require to add the Axios library in our project for handling the HTTP requests.
Axios can be installed with just one single command as below:
npm install axios
Step 4- Build Live Search Filter
Further, we need to create a new folder named as components/ in our React project.
Then, we create a LiveSearchFilter.js file into the components folder. Afterward, we will add the given code into it:
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;
We will be allowed to make HTTP Get request by importing the Axios at the top later.
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 the performance. To fix such an issue, we will use the cancelToken object. It will refrain the additional request from being sent.
We are just 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.
In the end, we will update the current state of the live search module and show the filtered results in the search filter dropdown.
Step 5- Update App Js File
For showing the search component on the browser, we will 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;
Step 6- Run Development Server
We have reached the last step of this guide where we need to run the React server. We can invoke the server using the given command:
npm start
Conclusion
So, friends, we have seen how to implement Live Search in a React app using Axios, REST API and React Hooks.
Hope that you have found this tutorial quite easy and simple to execute.
Good luck!