How to use multiple autocomplete values in Material UI?


An effective Autocomplete component is provided by the well-liked UI framework Material UI for React applications. Users can search and choose options from a predefined list as they type thanks to the autocomplete feature. Although choosing one option is the default behavior, there are some situations where we might want to give users the option of selecting multiple values.

In this article, we will explore how to implement and utilize multiple Autocomplete values in Material UI.

Multiple Autocomplete Values

Users can only choose one option at a time when using the Material UI Autocomplete component by default. Some scenarios, however, necessitate the selection of multiple options, such as tagging, selecting multiple categories, or allowing users to enter several related entities at the same time. Implementing multiple Autocomplete values improves the user experience by increasing flexibility and efficiency.

Multiple values in Autocomplete Props

  • multiple − It is a boolean type of prop that is used in selecting multiple values in an autocomplete component. If true, the value must be an array of items or options to allow multiple selections.

  • value − It is any type of prop that is used to manage the selected values in the component. The value must have reference equality with the option in order to be selected.

  • onChange − It is a function prop that is a callback function that triggers only when selected values change and has two parameters: the event object and the updated array of selected values.

  • getOptionLabel − It defines how the option labels are displayed in the Autocomplete. It should be a function that takes an option object as an argument and returns the label to be shown for that option.

Steps to Use Multiple Autocomplete Values

To use multiple values in material ui, there are some necessary steps to follow in order to do implement the multiple values effectively. Below is a complete step by step guide for the same:

Step 1: Import the material and its modules

The first and foremost step to use multiple values in Material UI is that we need to import the component and some of the necessary modules.

import TextField from "@mui/material/TextField"; //texfield for rendering input
import Autocomplete from "@mui/material/Autocomplete"; // importing autocomplete from mui
import Chip from "@mui/material/Chip"; //for displaying multiple values

Step 2: Define the Autocomplete component

Once we have imported the autocomplete component in react, we can now define the component in our react app.

<Autocomplete
   multiple
   options={data}
   renderInput={(params) => (
      <TextField
         {...params}
         label="Select language"
         placeholder="Programming languages"
      />
   )}
/>

Step 3: Use the renderTags prop

To add or select multiple values in autocomplete component, we use the renderTags prop in the autocomplete component. Below is the syntax on how to add the prop in the component.

renderTags={(tagValue, getTagProps) =>
   tagValue.map((item, index) => (
      <Chip
         label={item.label}
         {...getTagProps({ index })}
         disabled={fixedVal.indexOf(item) !== -1}
      />
   ))
}

Example 1

The below example displays adding multiple values in autocomplete with some fixed values.

import React, { useState } from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";
import Chip from "@mui/material/Chip"; //for displaying multiple values

const data = [
   { label: "Java language" },
   { label: "Python language" },
   { label: "C++ language" },
   { label: "C language" },
   { label: "Go language" },
   { label: "JavaScript language" },
   { label: "SQL" },
   { label: "MySQL" },
   { label: "HTML" },
   { label: "CSS" },
   { label: "Nextjs " },
   { label: "ReactJS " },
   { label: "VueJS " },
   { label: "Angular " },
   { label: "Angular JS " },
   { label: "PHP language" },
   { label: "R language" },
   { label: "Objective C language" },
   { label: "Cobol language" },
   { label: "Perl language" },
   { label: "Pascal language" },
   { label: "LISP language" },
   { label: "Fortran language" },
   { label: "Swift language" },
   { label: "Ruby language" },
   { label: "Algol language" },
   { label: "Scala language" },
   { label: "Rust language" },
   { label: "TypeScript language" },
   { label: "Dart language" },
   { label: "Matlab language" },
   { label: "Ada language" },
   { label: ".NET language" },
   { label: "Bash language" },
];

export default function App() {
   const fixedVal = [data[2]];
   const [val, setVal] = useState([...fixedVal]);
   const CustomChip = (chipVal, getTagProps) => {
      return chipVal.map((item, index) => (
         <Chip
            label={item.label} //adding options label
            {...getTagProps({ index })}
            disabled={fixedVal.indexOf(item) !== -1}
         />
      ));
   };

   return (
      <div
         style={{
            display: "flex",
            marginTop: 30,
            flexDirection: "column",
            alignItems: "center",
            justifyContent: "center",
         }}>
         <Autocomplete
            multiple
            onChange={(event, newValue) => {
               setVal([
                  ...fixedVal,
                  ...newValue.filter((i) => fixedVal.indexOf(i) === -1),
               ]);
            }}
            value={val}
            options={data}
            renderInput={(params) => (
               <TextField
                  {...params}
                  label="Select language"
                  placeholder="Programming languages"
               />
            )}
            renderTags={CustomChip}
         />
      </div>
   );
}

Output

Example

The below example displays the addition of a limited number of multiple values in autocomplete.

import React, { useState } from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";

const data = [
   { label: "Java language" },
   { label: "Python language" },
   { label: "C++ language" },
   { label: "C language" },
   { label: "Go language" },
   { label: "JavaScript language" },
   { label: "SQL" },
   { label: "MySQL" },
   { label: "HTML" },
   { label: "CSS" },
   { label: "Nextjs " },
   { label: "ReactJS " },
   { label: "VueJS " },
   { label: "Angular " },
   { label: "Angular JS " },
   { label: "PHP language" },
   { label: "R language" },
   { label: "Objective C language" },
   { label: "Cobol language" },
   { label: "Perl language" },
   { label: "Pascal language" },
   { label: "LISP language" },
   { label: "Fortran language" },
   { label: "Swift language" },
   { label: "Ruby language" },
   { label: "Algol language" },
   { label: "Scala language" },
   { label: "Rust language" },
   { label: "TypeScript language" },
   { label: "Dart language" },
   { label: "Matlab language" },
   { label: "Ada language" },
   { label: ".NET language" },
   { label: "Bash language" },
];

export default function App() {
   return (
      <div
         style={{
            display: "flex",
            marginTop: 30,
            flexDirection: "column",
            alignItems: "center",
            justifyContent: "center",
         }}>
         <Autocomplete
            multiple
            limitTags={3} // displays only 3 max tags of autocomplete when not in focus
            options={data}
            getOptionLabel={(option) => option.label}
            renderInput={(params) => (
               <TextField
                  {...params}
                  label="Select language"
                  placeholder="Programming languages"
               />
            )}
         />
      </div>
   );
}

Output

Conclusion

Multiple Autocomplete values can be implemented in Material UI, which is a useful addition for web applications that need users to input data in a flexible and effective manner. Using React, we learned how to use multiple values in a Material UI autocomplete component in the article. This feature can be easily added to your React project by following the step-by-step instructions and using the provided example. This improves the overall usability and interactivity of your application by enabling users to quickly choose multiple options from a predefined list.

Updated on: 30-Oct-2023

263 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements