Search Filter with React js

Bhavya Ambasta
Crobyer
Published in
3 min readApr 3, 2019

React js can be very handy when it comes to the use of API and data storage. The response recorded from an API call can be used across the application using ‘states’ the one big thing that makes React js one of the most effective client-side scripting language.

One of the functionality that is widely used for a variety of web application is Search.

React js makes it easy to implement search on data sets that are locally present after an API call which prevents multiple database hits.

Let’s start building a search using React js.

A sample JSON file that contains information of people.

The JSON contains name age and country to which these people belong to.

Now, in order to render this to your screen import the info-json.js file in App.js

The code :

Now the next step would be to parse the array of objects. In order to parse the array of objects, we need to use a map function that returns a new array and display it on the viewport.

The code:

At this point, the viewport(browser window) would look like this.

Mapping the json on screen.

Now we need to add a search box.

The code:

Now the viewport contains a search box also

with search box

And finally how the search would work.

In order to make the search work, we need to add a filter function with the map function which filters data based on the requirement but before that, we need to set up the state which would change as the content in search box changes. So, lets first configure the state.

The code:

setup state

As in the code snippet, the state contains a variable called search which is initially set to null. Now let's configure our search and show the search result. For this, we need to add a function that captures the event of the search box on change and set the value of the search box to the state variable.

The code:

And the final step filter configuration. The filter configuration is fairly simple. The filter acts as a data feeder to the map function wherein the data is segregated based on the search variable for which we check if the data includes the keywords which are present in this.state.search variable and feeds the data to the map function.

Here is the code:

And our react real-time search is ready.

The entire project can be found on https://github.com/kbhavya1/reactjs-search-filter

Please leave you reviews and modification. Thanks

--

--