Search code examples
javascriptreactjsmaterial-uiautocompleteblur

Material UI autocomplete closes on click when it was supposed to display a popover


I am trying to add a button to the Material UI autocomplete throgh the renderOption prop and added a button at each row which was supposed to display a PopOver component, but clicking on the button automatically closes the autocomplete search results

How can I prevent the autocomplete search results from closing on click

Here is a sandbox with my code: https://codesandbox.io/s/compassionate-rgb-z88y10

I have already checked this other similar issue, but in my case I am trying to set thr renderOption prop and not the PaperComponent But unfortunatelly in my case it wasn´t enough to just set the function to run on the onMouseDown event handler


Solution

  • You can create a controlled Autocomplete by using the open prop on the component. The onClose gives you various reasons why the Popover wants to close, you can find them all in the MUI docs.

    We check if the reason is selectOption if it is we do nothing and return out. If it is not we set isOpen to false to close the Popover

    const [isOpen, setIsOpen] = useState(false);
    
    return (
      <Autocomplete
        renderOption={(props, label) => (
          <PopOver
            {...props}
            id={props.id}
            label={label.label}
            message={label.label}
          />
        )}
        id="combo-box-demo"
        open={isOpen}
        onOpen={() => setIsOpen(true)}
        onClose={(e, reason) => {
          if (reason === "selectOption") return;
          setIsOpen(false);
        }}
        options={top100Films}
        sx={{ width: 300 }}
        renderInput={(params) => <TextField {...params} label="Movie" />}
      />
    );