Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material UI autocomplete popper custom closes on click

I am trying to add a button to the Material UI autocomplete paper by overriding the PaperComponent prop and added a button at the button of the paper, but clicking on the button automatically closes the autocomplete search results

How can i prevent the autocomplete search results Paper from closing on click

Here is a sandbox: https://codesandbox.io/s/material-demo-mxjyi

UPDATE: I didn't notice that the sandbox did not save, now you can see the issue

like image 487
WalksAway Avatar asked Nov 06 '25 18:11

WalksAway


2 Answers

The problem is the onBlur which occurs before your onClick. Material UI offers to ignore the blur behaviour on debug mode but that happens only if you have a value inside your Autocomplete.

The workaround is to use onMouseDown instead of onClick

Based on your Codesanbox please change the onClick event to onMouseDown event in your <button> component

<button
   style={{ margin: "10px", padding: "5px" }}
   onMouseDown={() => alert("clicked")}
>

The problem, which is not Material-UI related, was discussed here also

like image 125
Sabbin Avatar answered Nov 09 '25 08:11

Sabbin


using onMouseDown on the button is not the proper solution here as the user is expecting a different behavior. You can call preventDefault on the paper component to prevent it from closing.

<Autocomplete
  //other props...
  PaperComponent={(props) => (
    <Paper onMouseDown={event => event.preventDefault()}>
      <Button>Click</Button>
    </Paper>
  )}
/>
like image 44
user3377364 Avatar answered Nov 09 '25 10:11

user3377364