Implementing a Reusable Search Bar in ReactJS

Agnes Muita
4 min readJul 19, 2022
Search Functionality!

When building a React App, you may want your users to easily search and obtain precise results. The search functionality filters through data and displays information in a really cool way, and I will show you how.

For this tutorial, we will be getting users from an API(“https://jsonplaceholder.typicode.com/users”) that returns an array of users.

We begin by creating a SearchBar component that returns an input field and a data-displaying field. To make it reusable, we will implement props that are passed in the component as {placeholder, data}. This search bar can now be used in different parts of the application.

import React from ‘react’function SearchBar({placeholder, data}) {return (    <div className=”search”>      <div className=”searchInputs”>        <input type=”text” placeholder={placeholder}/>      </div>      <div className=”dataResults”></div>    </div>)
}
export default SearchBar;

In the app.js, we then import the SearchBar component at the top, and add it as the component to render inside the App component. The placeholder of the input is then passed into the SearchBar component and assigned a string “Enter a user..”.

We will then perform a GET request from the API using axios to return users using React’s useEffect hook. Use npm i axios to install axios and then add it as an import to your parent component. The data returned is stored in the users state and passed into the component as a prop.

import React,{useState, useEffect} from ‘react’import axios from ‘axios’;import ‘./App.css’import SearchBar from ‘./components/search’;
function App() { const [users, setUsers ] = useState([]) useEffect(()=>{ axios.get(“https://jsonplaceholder.typicode.com/users") .then(res=>{ setUsers(res.data) }) },[]) console.log(users) return ( <div> <div className=’layout-row justify-content-center mt-50'> <div className=’layout-column w-30'> <SearchBar placeholder=”Enter a user..” data={users} /> </div> </div> </div>
)
}export default App;

We then start implementing the logic for filtering the data in the SearchBar component as shown below. We loop through our data passed through props from the parent component, and use the map function. For each element of the array, we get a value and key, and return a list of the users.

import React from ‘react’function SearchBar({placeholder, data}) {return (    <div className=”search”>       <div className=”searchInputs”>          <input type=”text” placeholder={placeholder}/>       </div>       <div className=”dataResults”>        {data.map((value, key)=>{             return <div key={key}>{value.name}</div>         })}       </div>    </div>)}export default SearchBar;

Now the result will be a list of names displayed on the UI as shown below:

A list of all user names fetched from the API

The next interesting part is to filter this data based on the words inputted in the search bar . We do this by importing the useState hook, creating a state that will hold the filtered data, and setting it into an empty array.

const[filteredData, setFilteredData] = useState([])

However, we only want to display dataResults from the API when the filteredData is not empty i.e when someone starts typing. We wrap our data in Javascript as shown below. I have implemented the ternary operator to display dataResults only when the filteredData array is not empty, else I display the text “no user found”.

{filteredData.length !== 0 ? (    <div className="dataResults">     {data.map((value, key)=>{       return <div key={key} className="dataItem">{value.name}</div>     })}   </div>) : (<div> <h3>No Movie Found</h3></div>)}
Display “no user found” when there is no result

We then create logic to populate the filteredData array and filter through that data. Therefore, we pass a function, handleChange, to the input. This function is called every time there are changes to the input, and it dynamically filters through the data to find a matching user name to the search words.

<input type=”text” placeholder={placeholder} onChange={handleChange}/>const handleChange = (e)=>{   const wordEntered = e.target.value;   const newFilter = data.filter((value)=>{     return value.name.toLowerCase().includes(wordEntered)  })   setFilteredData(newFilter)}

The handleChange function takes in an event(e) that represents the event of the input. We then access e.target.value and store it in a variable called wordEntered. This represents the words being searched from the search bar. We then filter through the data from the API to get the names of users that are similar to the name being inputted in the search bar. We convert to lowercase using toLowerCase() to account for both uppercase and lowercase search words.

We can then set the filteredData to the newFilter array we just created. As a result, we now filter through filteredData rather than data.

{filteredData.length !== 0 ? (  <div className=”dataResults”>     {filteredData.map((value, key)=>{       return <div key={key} className=”dataItem”>{value.name}</div>     })}  </div>) : (<div> <h3>No user found</h3></div>)}

The final code for the SearchBar component is as follows:

import React,{useState} from ‘react’function SearchBar({placeholder, data}) {   const[filteredData, setFilteredData] = useState([])   const handleChange = (e)=>{     const wordEntered = e.target.value;     const newFilter = data .filter((value)=>{       return value.name.toLowerCase().includes(wordEntered)     })     setFilteredData(newFilter)    }return (   <div className=”search”>     <div className=”searchInputs”>       <input type=”text” placeholder={placeholder} onChange={handleChange}/>    </div>    {filteredData.length !== 0 ? (        <div className=”dataResults”>        {filteredData.map((value, key)=>{       return <div key={key} className=”dataItem”>{value.name}</div>        })}       </div>     ) : (<div> <h3>No user found</h3></div>)     }  </div>)}export default SearchBar;

And Voila! You can now display the names of users that contain the search words typed in the search bar. You’re welcome.

Also, find my previous article here:https://agnesmuita.medium.com/cors-error-solved-access-to-fetch-has-been-blocked-by-cors-policy-d74b17cada92

--

--