How to customize autocomplete components in Material UI?


In this article, we will learn how to customize the autocomplete components in Material UI.

Popular React UI framework Material UI provides a wide range of components with contemporary and elegant designs. Autocomplete, which offers users suggestions in real−time as they work with input fields, is one such flexible component.

Autocomplete components can be easily customized also with the help of some props that are available in the documentation of Material UI. The props like renderTags and renderInput can help customize the input autocomplete component.

The Autocomplete component not only improves the user experience but also allows for seamless customization, giving developers the ability to modify its look, behavior, and style to suit the particular needs of their application.

Autocomplete Customization Props

There are different props that are used in customizing the autocomplete component. Let’s see all of these props in detail −

  • renderInput − This prop is used in rendering the input. This is the mandatory prop when it comes to use the autocomplete component.

  • renderTags − This prop is used in rendering the Tags. It renders only the selected value that is provided to the component.

  • renderOption − This prop renders the option, and along with this, it uses the getOptionLabel by default.

  • getOptionLabel − This prop determines the string value for a given option. It's used to fill the input (and the list box options if renderOption is not provided).

    If used in free solo mode, it must accept both the type of the options and a string.

  • filterOptions − This prop is a function used in finding the filtered options to be rendered on search.

The above props are some of the commonly used one’s but they are not limited to. There are other props also that are used in the autocomplete component.

Syntax

Below is the common syntax for customization of an autocomplete component −

<Autocomplete
   multiple
   renderTags={(value, getTagProps) =>
      value.map((item, index) => (
         <Chip
            key={index}
            label={item.label}
            {...getTagProps({ index })}
         />
      ))
   }
   getOptionLabel={(item) => item.label}
   sx={{
      display: "inline-block",
   }}
   options={data}
   renderInput={(params) => (
      <div {...params}>
         <input {...params} />
      </div>
   )}
/>

Example

The below example demonstrates a custom autocomplete component with multiple value selections in Material UI.

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

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",
         }}>
         <h3>Select language</h3>
         <Autocomplete
            multiple
            renderTags={(value, getTagProps) =>
               value.map((item, index) => (
                  <Chip
                     key={index}
                     label={item.label}
                     {...getTagProps({ index })}
                  />
               ))
            }
            getOptionLabel={(item) => item.label}
            sx={{
               display: "inline-block",
            }}
            options={data}
            renderInput={(params) => (
               <TextField
                  sx={{
                     width: 300,
                     bgcolor: "lightgreen",
                     fontSize: 20,
                     color: "black",
                     borderColor: "green",
                  }}
                  {...params}
               />
            )}
         />
      </div>
   );
}

Output

Example

The below example demonstrates a custom autocomplete input component in Material UI.

In this example, we have customized the autocomplete component with the custom styles like background color, text color, font size, etc. and apart from this we have also customized the input div with the respective params.

import React from "react";
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",
         }}>
         <h3>Select language</h3>
         <Autocomplete
            sx={{
               "& input": {
                  width: 300,
                  padding: 2,
                  bgcolor: "lightgreen",
                  fontSize: 20,
                  color: "black",
                  borderRadius: 10,
               }
            }}
            options={data}
            renderInput={(params) => (
               <div ref={params.InputProps.ref}>
                  <input {...params.inputProps} />
               </div>
            )}
         />
      </div>
   );
}

Output

Example

The below example demonstrates a hint in a custom autocomplete input component in Material UI. In this example, we have added the hint feature also, where when the user writes any input, it displays the matched results. We have used renderInput and filterOptions to achieve this.

import * as React from "react";
import { TextField } from "@mui/material/";
import { Autocomplete } from "@mui/material/";

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" },
];

// main App component rendering the custom autocomplete component
export default function App() {
   var getHint = React.useRef("");
   const [val, setVal] = React.useState("");

   return (
      <div
         style={{
            display: "flex",
            marginTop: 30,
            flexDirection: "column",
            alignItems: "center",
            justifyContent: "center",
         }}>
         <Autocomplete
            onKeyDown={(event) => {
               if (event.key === "Tab") {
                  if (getHint.current) {
                     setVal(getHint.current);
                     event.preventDefault();
                  }
               }
            }}
            onBlur={() => {
               getHint.current = "";
            }}
            disablePortal
            inputValue={val}
            filterOptions={(options, state) => {
               const showItems = options.filter((item) =>
                  item.label
                  .toLowerCase()
                  .trim()
                  .includes(state.inputValue.toLowerCase().trim())
               );

               return showItems;
            }}
            options={data}
            renderInput={(params) => {
               return (
                  <div sx={{ position: "relative" }}>
                     <div>{getHint.current}</div>
                     <TextField
                        {...params}
                        onChange={(event) => {
                           const selNewVal = event.target.value;
                           setVal(selNewVal);
                           const matchItem = data.find((option) =>
                              option.label.startsWith(selNewVal)
                           );

                           if (selNewVal && matchItem) {
                              getHint.current = matchItem.label;
                           } else {
                              getHint.current = "";
                           }
                        }}
                        label="Select language"
                     />
                  </div>
               );
            }}
            sx={{ width: 400 }}
         />
      </div>
   );
}

Output

Conclusion

We looked at a few different ways to customize the Material UI Autocomplete component. To seamlessly adapt the Autocomplete to fit the design and functionality of your application by changing the size, styles, suggestions, and handling of selected values. The adaptability and extensive customization options of Material UI make it a potent tool for designing delightful user experiences.

Create intuitive and aesthetically pleasing Autocomplete components for our Material UI−powered applications by experimenting with various customization options and letting your creativity run wild.

Updated on: 30-Oct-2023

88 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements