How to Create Dynamic Search Filter in React Js

This quick React search filter guide will teach you how to create a dynamic list of items that we will render from the server.

And filter the items from the list based on the values provided by the user in the HTML input field.

The search filter is usually an input field where a user diligently enters the text, the desired result or items pop up in front of the user just below the input field.

The list items appear based on how much the entered text in an input resembles the data presented in the result object. If the whole text matches, you will see the single or multiple items or somewhat similar to the query.

To build the React search filter component, we will use the Axios library in the class component. The Axios library does a great job in relation to fetching the result from the server, and it takes an API that works with HTTP protocols.

To properly create a search filter for list items, we will take the help of popular built-in JavaScript methods such as filter() and indexOf(). So, let’s get started.

React Js Dynamic Search Filter for List View Example

  • Step 1: Install Blank New Project
  • Step 3: Create Search Filter
  • Step 4: Add CSS Design in Filter
  • Step 5: Register Component
  • Step 6: Run in Browser

Install Blank New Project

Commence the first step by installing a brand new blank React project.

npx create-react-app react-bey

Take a step inside the application directory.

cd react-bey

You may undoubtedly jump on to the subsequent instruction if you already have the project ready.

Create Search Filter

Go to `components` folder, likewise create the /SearchFilter.js file.

The following code should be added to the file, allowing you to create the search filter component in React.

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


export default class SearchFilter extends Component {
  constructor(props) {
    super(props)
    this.state = {
      Users: [],
    }
    this.node = React.createRef()
  }

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

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

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

  onUserChange = async (e) => {
    await axios
      .get('https://www.testjsonapi.com/users/')
      .then((res) => {
        this.setState({
          Users: res.data,
        })
      })
      .catch((err) => {
        console.log(err)
      })

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

    let resUser = this.state.Users.filter((e) => {
      let dataFilter = e.name.toLowerCase()
      return dataFilter.indexOf(filter) !== -1
    })

    this.setState({
      Users: resUser,
    })
  }

  render() {
    return (
      <div className="filterBlock">
        <h2>React Js Search Filter Example - RemoteStack.io</h2>
        <input
          type="text"
          onClick={this.onChange}
          onChange={this.onUserChange}
          placeholder="Search ..."
          ref={this.node}
        />
        <ul>
          {this.state.Users.map((res) => {
            return <li key={res.id}>{res.name}</li>
          })}
        </ul>
      </div>
    )
  }
}

Add CSS Design in Filter

If you know css than you can give the diffrent look to search filter.

However, if you don’t know than open the index.css and insert the following code into the file.

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

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

.filterBlock {
  width: 470px;
  color: #222;
}

.filterBlock input {
  padding: 16px;
  outline: none;
  border: none;
  width: 100%;
  font-size: 1.28rem;
  background-color: #ffffff;
  border: 1px solid transparent;
}

.filterBlock ul {
  overflow: hidden;
  overflow-y: auto;
  width: 100%;
  margin-top: 15px;
  padding: 0 16px;
  max-height: 320px;
  background-color: #ffffff;
}

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

.filterBlock li:hover {
  color: rgb(248, 21, 82);
}

Register Component

To filter the list items utterly, you must ensure the search filter component is added to the App.js template.

Here is the code that does what we aimed.

import React from 'react'
import SearchFilter from './components/SearchFilter'

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

Run in Browser

You must be wondering how does it work?

Well, fret not! Just start the app through below command and view app in the browser.

npm start

How to Create Dynamic Search Filter in React Js

Summary

This comprehensive guide has described how to make the search filter component, which takes the user input and fetches the result from the server, and displays it in the list view.

Also, we used the React concepts like state, lifecycle methods, etc. to create the filter search module. We will use the input field to attach event handlers to it and display the list item after filtering using the map() method.