Remove highlight on mouse leave in MUI Autocomplete

Viewed 792

Using Autocomplete and hovering over the list of options, and moving the mouse out of it leaves the latest option, that the mouse was hovering over, still highlighted.

What's the best way to remove highlight when the mouse pointer is outside of the list altogether?

1 Answers

You can add mouseenter and mouseleave handlers to know when the mouse is inside the Listbox and override the background if the mouse is outside and the option is focused. Note that the double ampersand is necessary to increase the CSS specificity and put your styles above the one from MUI:

const [mouseInListBox, setMouseInListBox] = React.useState(false);

return (
  <Autocomplete
    {...props}
    ListboxProps={{
      onMouseEnter: () => setMouseInListBox(true),
      onMouseLeave: () => setMouseInListBox(false),
      sx: {
        '&& li.Mui-focused': {
          bgcolor: !mouseInListBox ? 'white' : undefined,
        },
      },
    }}
    renderInput={(params) => <TextField {...params} label="Movie" />}
  />
);

Live Demo

Codesandbox Demo

Related