reactjsmaterial-uimui-autocomplete

Material UI 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


Solution

  • 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.

    /* 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