How to Implement Search in React JS with JSON

How to filter data or implement search option using ReactJS with JSON. There are various different methods to implement the Search options on the web page. In this ReactJS tutorial, we will see some simple examples to Implement Search in ReactJS using  fliter() function.

Filter function in Javascript

filter() calls a provided callback function once for each element in an array and constructs a new array of all the values for which the callback function returns a value that coerces to true.

The callback function is invoked only for indexes of the array which have assigned values; it is not invoked for indexes that have been deleted or which have never been assigned values.

Array elements that do not pass the callback function test are skipped and are not included in the new array.

Callback Function is invoked with three arguments:

1. the value of the element
2. the index of the element
3. the Array object being traversed

How to Implement Search in React JS with JSON

Let’s create a simple ReactJs application to implement Search in ReactJS with JSON. below are some simple steps just follow them with me.

1. Create react app

npx create-react-app search

2. Add a JSON file containing JSON data for searching purposes (eg:- MOCK_DATA.json in the below example )
3. Import state hook, react and JSON data file in app.js along with CSS files.

import React,{useState} from 'react'
import './App.css';
import JSONDATA from './MOCK_DATA.json'

4. Create a state to store search characters.

const [searchTerm,setSearchTerm] = useState('')

5. Use filter functions to drop other results except for search character included using includes() function and passing search character as argument
6. Use a Conditional statement to check if the search bar is empty or not accordingly showcase the result.

{JSONDATA.filter((val)=>{
        if(searchTerm == ""){
          return val
        }
        else if(val.first_name.toLowerCase().includes(searchTerm.toLowerCase())){
          return val;
        }
      }).map((val,key)=>{
        return <div>{val.first_name} </div>
      })}

App.js file altogether

import React,{useState} from 'react'
import './App.css';
import JSONDATA from './MOCK_DATA.json'

function App() {

  const [searchTerm,setSearchTerm] = useState('')

  return (
    <div className="App">
      <input type="text" placeholder="seach..." onChange={e=>setSearchTerm(e.target.value)} />
      {JSONDATA.filter((val)=>{
        if(searchTerm == ""){
          return val
        }
        else if(val.first_name.toLowerCase().includes(searchTerm.toLowerCase())){
          return val;
        }
      }).map((val,key)=>{
        return <div>{val.first_name} </div>
      })}
    </div>
  );
}

export default App;

Output

Enlarged/Cropped

List Before Searching when the search bar is empty.

Enlarged/Cropped

This result shows all the names that start with ‘x’ character or the name which contains this.