How to create a dynamic search box in ReactJS?


Search is one of the most important functionalities of the website. It allows users to filter products and search for specific things on the website, reducing the time users find particular things on the website.

For example, you can see a search bar at the top of this page. Whenever we enter any search input, it shows us a search result by filtering the courses and tutorials based on the search result.

This tutorial will teach us to implement dynamic search from scratch in ReactJS.

Use the AutoComplete Component of Material UI

The Material UI library contains various built-in components which we can use in our React app directly. It also contains the ‘AutoComplete’ component, which we can use as a search in the React app. It takes various values as props and behaves according to the props we pass.

Syntax

Users can follow the syntax below to use MaterialUI’s AutoComplete component to implement dynamic search.

<Autocomplete
   autoComplete
   options={myOptions}
   renderInput={(data) => (
      <TextField {...data} variant="outlined" label="Search Box" />
   )}
/>

In the above syntax, we have passed the Textfield to render and myOptions as all search options.

Example

In the example below, we have used the useEffect() hook to fetch all data from API. After that, using the API data, we created the object containing the label. The label of all objects in the myOptions array should be unique, and we can search labels in the search component.

import React, { useEffect, useState } from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
export default function App() {
   const [myOptions, setMyOptions] = useState([]);
   function getData() {
      
      // fetch data
      fetch("https://jsonplaceholder.typicode.com/users")
      .then((response) => {
         return response.json();
      })
      .then((res) => {
         for (var i = 0; i < res.length; i++) {
            if (!myOptions.some((obj) => obj.label == res[i].name)) {
               
               // create an object with a label
               let object = {
                  label: res[i].name,
                  usersName: res[i].username,
               };
               myOptions.push(object);
            }
         }
         setMyOptions(myOptions);
      }); 
   }
   useEffect(() => getData(), [myOptions]);
   return (
      <div>
         <h2>
         {" "}
         Using the <i> Material UI Autocomplete </i> component to implement search. </h2>
         <Autocomplete
            Style = {{ width: 400 }}
            autoComplete
            autoHighlight
            freeSolo
            options = {myOptions}
            renderInput = {(data) => (
               <TextField {...data} variant = "outlined" label = "Search Box"/>
            )}
         />
      </div>
   );
}

Output

Create Dynamic Search From Scratch Using ReactJS

We can create an array of all values or objects in ReactJS. After that, when a user searches for any value, we can use the filter() method to filter all objects from the array matching the search input value. We can use the match() method to check whether the input matches the current object property.

Syntax

Users can follow the syntax below to filter objects in the array based on the searched input value.

let filteredCountries = countries.filter((country) => {
   return country.name.match(searchInput.toLowerCase());
});
const filtered = filteredCountries?.map((country) => (
   
   // return mapped values
));

In the above syntax, we have used the filter() and match() methods to filter all objects based on the search value, and after that, we used the map() method to map object values into the array.

Example

In the example below, we have created the array of countries containing the object with name and population properties. After that, whenever the user changes to input, we invoke the handleChange() function, which filters the objects based on the search value.

Next, we used the map() method to map the filter value to the table column. In the component, we have invoked the searchList() function, which returns all filtered countries.

import React, { useState } from "react";
export default function App() {
   const [searchInput, setSearchInput] = useState("");
   let countries = [
      { name: "china", population: 1439323776 },
      { name: "india", population: 1380004385 },
      { name: "usa", population: 331002651 },
      { name: "indonesia", population: 273523615 },
      { name: "pakistan", population: 220892340 },
      { name: "canada", population: 37742154 },
      { name: "new zealand", population: 4822233 },
      { name: "italy", population: 60461826 },
      { name: "south africa", population: 59308690 },
      { name: "rusia", population: 154934462 },
      { name: "egypt", population: 102334404 },
      { name: "iran", population: 83992949 },
      { name: "france", population: 65273511 },
      { name: "mexico", population: 128932753 },
      { name: "spain", population: 46754778 },
      { name: "senegal", population: 16743927 },
      { name: "brazil", population: 212559417 },
      { name: "denmark", population: 5792202 },
      { name: "sudan", population: 43849260 },
      { name: "iraq", population: 40222493 },
      { name: "peru", population: 32971854 },
      { name: "bangladesh", population: 164689383 },
      { name: "portugal", population: 10196709 },
   ];
   const handleChange = (e) => {
      e.preventDefault();
      setSearchInput(e.target.value);
   };
   function searchList() {
      
      // filter countries according to search values
      let filteredCountries = countries.filter((country) => {
         return country.name.match(searchInput.toLowerCase());
      });
      
      // create table rows
      const filtered = filteredCountries?.map((country) => (
         <tr>
            <td> {country.name}</td>
            <td> {country.population} </td>
         </tr>
      ));
      return <div> {filtered} </div>;
   }
   return (
      <div>
         <h2>
            {" "}
            Creating the <i> dynamic search </i> component to implement search.
         </h2>
         <input
            Type="search"
            placeholder="Search here"
            onChange={handleChange}
            value={searchInput}
         />
         <table style={{ tableLayout: "fixed", width: "11rem" }}>
            <tr>
               <th> Country </th>
               <th> population </th>
            </tr>
            {searchList()}
         </table>
      </div>
   );
}

Output

Users learned to create a dynamic search component using Material UI and pure JavaScript. The Material UI AutoComplete component contains various props to manipulate components so users can use it. Users who need more customizations that Material UI is not providing can create their own search using the second approach.

Updated on: 06-Mar-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements