React

React Material UI Autocomplete Component Example Tutorial

Pinterest LinkedIn Tumblr

To create an autocomplete component in React using Material-UI, you can use the Autocomplete component. Here is an example:

Copy codeimport { Autocomplete } from "@material-ui/lab";

const options = ["Option 1", "Option 2", "Option 3"];

function AutocompleteExample() {
  const [value, setValue] = React.useState(null);

  return (
    <Autocomplete
      options={options}
      getOptionLabel={(option) => option}
      value={value}
      onChange={(event, newValue) => setValue(newValue)}
      renderInput={(params) => (
        <TextField {...params} label="Select an option" variant="outlined" />
      )}
    />
  );
}

In this example, we first import Autocomplete from ‘@material-ui/lab’. We create an array of options to show in the autocomplete and create a state variable called “value” to keep track of the selected option.

We pass the options and the value to Autocomplete component and handle onChange event for the Autocomplete component and update the “value” state variable with the newValue passed on onChange.

We also pass a renderInput prop which accepts a function which receives an object called params and return the JSX that should be rendered as the input field.

We used TextField component from Material-UI and passed the params props to it and added a label and variant to it.

You can customize the Autocomplete component using the various props available on the Autocomplete component, such as “autoComplete”, “disableClearable”, “disableCloseOnSelect” etc.

For example, you can enable autocomplete by setting the “autoComplete” prop to true, or you can disable the clear button by setting the “disableClearable” prop to true.

You can also customize the TextField component with different styles and props like the label and variant.

Copy coderenderInput={(params) => (
        <TextField {...params} label="Select an option" variant="outlined" style={{color: "green"}}/>
)}

In this example, I have added style to the TextField component and change the color to green.

You can also customize the option by passing the optionLabel and optionSelected props.

Copy code <Autocomplete
      options={options}
      getOptionLabel={(option) => option.name}
      getOptionSelected={(option, value) => option.name === value.name}
      value={value}
      onChange={(event, newValue) => setValue(newValue)}
      renderInput={(params) => (
        <TextField {...params} label="Select an option" variant="outlined" style={{color: "green"}}/>
      )}
    />

In this example, I have used the getOptionLabel and getOptionSelected props to customize the options and comparison to select the option.