Select Page

Hey devs, today we are going to talk a bit on react and how to create a search filter in React. First of all, the important thing to understand it that react is based on javascript and the function that we use to map an array and to filter it are javascript functions. Before we start, let’s create our array of objects.

const myArray = ["Italy","USA","UK,"France","Spain","Germany"]

Then we are going to create an input form. When the text of the input changes, we update the value of a variable (in my example is “filterName”) using useState.

...
    const [filterName, setFilter] = useState("")
...

return(
<form >
 <div >
   <label>Name</label>
    <input type="text" name="name" onChange=>{(e)=>     
    setFilter(e.target.value)} />
  </div>
</form>
)

After we do that we can create a component where we output the value of the array. In order to output values of an array, we have to map through it. Before we map the array, we have to check if the value of “filterName” is empty, in that case we won’t filter trough it, otherwise we have to filter it.

There are two ways to filter an array, the first way, takes the word the user inputted and compares it with each value of the array and checks if the two are equal or not. The second way does the same thing except that it check if the word inputted by the user is contained in each of the values of the array. We are going to see both of them.

myArray
  .filter((value) =>
  value.includes(filterName)
  )
  .map((val, index) => {
      <div> 
        {value}
       </div>
}

In this example, we are filtering the array and checking which of the values of the array contains the input of the user and then we map.

myArray
  .filter((value) =>
  value===filterName
  )
  .map((val, index) => {
      <div> 
        {value}
       </div>
}

In this example, we are checking if the values of the array are equals to the input of the user. If yes, that is mapped.

In order to create a search bar, we have to use the first example.

That is the end of this article. Hope that now you will be able to create a search filter in React!

Check other posts