D10001
D10001

Reputation: 153

MUI Autocomplete: How to prevent open on focus, instead open on input change?

I'm trying to stop the Autocomplete from opening the suggestions as soon as the user clicks. I'd like it to only open as the user begins typing. There doesn't seem to be a prop to achieve this. Could there be a way to use onInputChange to toggle the Autocomplete 'open' prop (bool). Thanks

Upvotes: 14

Views: 21709

Answers (1)

Ryan Cogswell
Ryan Cogswell

Reputation: 80986

Yes, you can explicitly control the open prop and if you want to base this on the user having typed something, then I recommend that you also explicitly control the inputValue prop as well.

Below is a working example of one way to do this. This specifies the onOpen, onClose, onInputChange, open, and inputValue props in addition to the props typically specified.

  • onOpen will get called by Material-UI whenever it thinks open should be set to true. handleOpen in the example below, ignores this event when the inputValue is empty.
  • onClose will get called by Material-UI whenever it thinks open should be set to false. The example below unconditionally calls setOpen(false) so that it still closes in all the same scenarios as in the default behavior.
  • handleInputChange in the example below, in addition to managing the inputValue state, toggles the open state based on whether the value is empty.
/* eslint-disable no-use-before-define */
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default function ComboBox() {
  const [inputValue, setInputValue] = React.useState("");
  const [open, setOpen] = React.useState(false);
  const handleOpen = () => {
    if (inputValue.length > 0) {
      setOpen(true);
    }
  };
  const handleInputChange = (event, newInputValue) => {
    setInputValue(newInputValue);
    if (newInputValue.length > 0) {
      setOpen(true);
    } else {
      setOpen(false);
    }
  };
  return (
    <Autocomplete
      id="combo-box-demo"
      open={open}
      onOpen={handleOpen}
      onClose={() => setOpen(false)}
      inputValue={inputValue}
      onInputChange={handleInputChange}
      options={top100Films}
      getOptionLabel={option => option.title}
      style={{ width: 300 }}
      renderInput={params => (
        <TextField {...params} label="Combo box" variant="outlined" />
      )}
    />
  );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
  { title: "The Shawshank Redemption", year: 1994 },
  { title: "The Godfather", year: 1972 },
  { title: "The Godfather: Part II", year: 1974 }
// and many more options
];

Edit Autocomplete open if input

Upvotes: 19

Related Questions