Create an easy search filter in React

davidbell_xyz

David Bell

Posted on March 26, 2020

Create an easy search filter in React

Often you want search functionality in your React app. Here is a simple way to implement this using filter() and includes() array methods along with the useState Hook.

Firstly here is the boiler plate code that simply displays a list of dogs with no search functionality. The state is a hard coded array of objects called doggos.

import React, { useState } from "react"
import "./styles.css"

export const App = () => {
  const [doggos] = useState([
    { name: "Spike" },
    { name: "Winston" },
    { name: "Shandy" },
    { name: "Fluffy" },
  ])

  return (
    <div className="App">
      <ul>
        {doggos.map(dog => (
          <li>{dog.name}</li>
        ))}
      </ul>
    </div>
  )
}
export default App
Enter fullscreen mode Exit fullscreen mode

The resulting application for my example is a very basic list and search input. That displays all dogs until user types. Once typed only dogs containing those letters will display.

Result

  • Next we need to add some state for filtering as an empty string
const [doggos] = useState([
  { name: "Spike" },
  { name: "Winston" },
  { name: "Shandy" },
  { name: "Fluffy" },
])
const [dogFilter, setDogFilter] = useState("")
Enter fullscreen mode Exit fullscreen mode
  • Then add an an input with a onChange event in out App
    <div className="App">
      <input
        aria-label="Search"
        placeholder="Type to search..."
        type="text"
        onChange={handleSearchInput}
      />
Enter fullscreen mode Exit fullscreen mode

We have stated we call handleSearchInput on an onChangeevent so next we must create that function

const handleSearchInput = event => {
  setDogFilter(event.target.value)
}
Enter fullscreen mode Exit fullscreen mode

The above code takes an event and the setDogFilter is used to set the state of dogFilter to what is being typed. Adding a console.log(event.value.target) is a good idea to see for yourself.

  • Next create a function which filters through doggos state and returns the name that matches what is being types.
const filteredDogs = doggos.filter(dog =>
  dog.name.toLowerCase().includes(dogFilter.toLowerCase())
)
Enter fullscreen mode Exit fullscreen mode

You can see I have used the includes() array method.

  • The includes() method determines whether an array includes a certain value among its entries, returning true or false.

toLowerCase() is used because capital letters don't matter in this instance.

  • Now simply map over filteredDogs instead of doggos
<ul>
  {filteredDogs.map(dog => (
    <li>{dog.name}</li>
  ))}
</ul>
Enter fullscreen mode Exit fullscreen mode

Summary

There we have it. A simple search functionality in React using Hooks and some JavaScript array methods.
I'll include the final code below.

The Final Code

import React, { useState } from "react"
import "./styles.css"

export const App = () => {
  const [doggos] = useState([
    { name: "Spike" },
    { name: "Winston" },
    { name: "Shandy" },
    { name: "Fluffy" },
  ])
  const [dogFilter, setDogFilter] = useState("")

  const handleSearchInput = event => {
    setDogFilter(event.target.value)
  }

  const filteredDogs = doggos.filter(dog =>
    dog.name.toLowerCase().includes(dogFilter.toLowerCase())
  )
  return (
    <div className="App">
      <input
        aria-label="Search"
        placeholder="Type to search..."
        type="text"
        onChange={handleSearchInput}
      />
      <ul>
        {filteredDogs.map(dog => (
          <li>{dog.name}</li>
        ))}
      </ul>
    </div>
  )
}
export default App
Enter fullscreen mode Exit fullscreen mode

Let's connect

Twitter

πŸ’– πŸ’ͺ πŸ™… 🚩
davidbell_xyz
David Bell

Posted on March 26, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related