Fixed Options in Searchbox in ReactJS


Sometimes, developers require to add the fixed options in the search box while creating the search bar. For example, you are developing a web application containing different web pages related to cars, bikes, other vehicles, etc. Also, you require to add a search bar on every web page. So, you may be required to add the fix tags like car, bike, or some car or bike brands as fixed tag in the search bar to highlight.

In this tutorial, we will learn to add fixed options in search box in ReactJS using the AutoComplete component of the Material UI library.

Users can execute the below command in the React project to install the Material UI library.

npm install @mui/material @mui/styled-engine-sc styled-components

Syntax

Users should follow the syntax below to use the AutoComplete component of Material UI to add fixed options in the search bar.

<Autocomplete
   multiple
   onChange={(event, newValue) => {
      // set fixed and selected options
   }
   value={currentValues}
   options={searchOptions}
/>

In the above syntax, currentValues contains all selected values and fixed values.

Example 1

In the example below, we have used the AutoComplete component of Material UI to implement the search bar. We have stored the car brands in the array. Also, we have added the “BMW” as a fixed option.

After that, we have passed the ‘multiple’ attribute to the AutoComplete component to allow users to select multiple values. We have used the ‘searchOptions’ as an option of the AutoComplete component. Also, whenever the user selects or removes an option from the search bar, we change the value of ‘currentValues’ by adding selected and fixed options.

In the output, users can observe that ‘BMW’ is pre-selected, and users can’’t remove it as it is disabled.

import React, { useState } from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
import { Chip } from "@mui/material";
export default function App() {
   // Adding different car brands in search options
   let searchOptions = [
      "BMW",
      "Audi",
      "Mercedes",
      "Toyota",
      "Honda",
      "Ford",
      "Huyndai",
      "Kia",
      "Nissan",
      "Mazda",
      "Chevrolet",
      "Jeep",
      "Fiat",
      "Volkswagen",
      "Renault",
      "Volvo",
      "Suzuki",
      "Scion",
      "Smart",
      "Tesla"
   ];
   let fixedOptions = ["BMW"];
   let [currentValues, setValue] = useState([...fixedOptions]);
   return (
      <div>
         <h2>
            {" "}
            Using the <i> Material UI Autocomplete </i> component to implement fixed
            option search.{" "}
         </h2>
         <Autocomplete
            multiple
            Style={{ width: 400 }}
            autoComplete
            autoHighlight
            freeSolo
            onChange={(event, newValue) => {
               setValue([
                  ...fixedOptions,
                  ...newValue.filter((option) => fixedOptions.indexOf(option) === -1)
               ]);
            }}
            value={currentValues}
            options={searchOptions}
            renderInput={(data) => (
               <TextField {...data} variant="outlined" label="Search Box" />
            )}
         />
      </div>
   );
}

Output

Example 2

In the example below also, we have used the AutoComplete component to implement the search bar. Here, we extract the data for the search options from the API. From the API, we get multiple products as a response, and we use the titles of the product as a search option. Also, we have fixed two products title for the search options.

In the output, users can observe that two product titles are fixed in the search bar.

import React, { useState, useEffect } from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
export default function App() {
   // using the fetch API to get the data from the https://dummyjson.com/products
   const [searchOptions, setSearchOptions] = useState([]);
   const fetchSearchOptions = async () => {
      const response = await fetch("https://dummyjson.com/products");
      const data = await response.json();
      for (let i = 0; i < data.products.length; i++) {
         setSearchOptions((prev) => [...prev, data.products[i].title]);
      }
   };
   useEffect(() => {
      fetchSearchOptions();
   }, []);
   let fixedOptions = ["iPhone 9","OPPOF19"];
   
   //   fixedOptions.push(searchOptions[0]);
   
   //   fixedOptions.push(searchOptions[1]);
   let [currentValues, setValue] = useState([...fixedOptions]);
   return (
      <div>
         <h2>
            {" "}
            Using the <i> Material UI Autocomplete </i> component to implement fixed
            option search. {" "}
         </h2>
         <Autocomplete
            multiple
            Style={{ width: 400 }}
            autoComplete
            autoHighlight
            freeSolo
            onChange = {(event, newValue) => {
               setValue([
                  ...fixedOptions,
                  ...newValue.filter((option) => fixedOptions.indexOf(option) === -1),
               ]);
            }}
            value = {currentValues}
            options = {searchOptions}
            renderInput = {(data) => (
               <TextField {...data} variant="outlined" label="Search Box" />
            )}
         />
      </div>
   );
}

Output

Users learned to add fixed options to the search bar in ReactJS. Here, we have used the AutoComplete component to implement the search bar. Users can also explore the other variants of the Autocomplete component on the material UI’s official website.

Updated on: 24-Apr-2023

56 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements