WalksAway
WalksAway

Reputation: 2819

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

Upvotes: 4

Views: 7102

Answers (2)

user3377364
user3377364

Reputation: 181

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>
  )}
/>

Upvotes: 2

Sabbin
Sabbin

Reputation: 2445

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

Upvotes: 11

Related Questions