React onDragStart doesn't fire in Material UI Autocomplete component

Viewed 456

I've added an onDragStart handler to one of the options in a React Autocomplete component but it doesn't fire when dragging with the mouse. Here's a live demo: https://codesandbox.io/s/material-demo-forked-z2093?file=/demo.js

The relevant piece of code:

      renderOption={(option) => (
        <React.Fragment>
          <div
            draggable="true"
            onClick={(evt) => console.log("click")}
            onDragStart={(evt) => console.log("dragstart")}
          >
            <span>{countryToFlag(option.code)}</span>
            {option.label} ({option.code}) +{option.phone}
          </div>
        </React.Fragment>
      )}

I added the onClick handler as a point of reference to show that some events are firing. Any ideas on how I can get onDragStart to do something when the dropdown is opened and I start dragging one of the options (countries in the example above)?

1 Answers

I think the issue is that the Autocomplete calls preventDefault on mouse-down events:

    getListboxProps: () => ({
      role: 'listbox',
      id: `${id}-popup`,
      'aria-labelledby': `${id}-label`,
      ref: handleListboxRef,
      onMouseDown: (event) => {
        // Prevent blur
        event.preventDefault();
      },
    }),

This call to preventDefault prevents the drag from starting. You can avoid this call to preventDefault by stopping propagation of the mouse-down event, but then (as indicated by the comment in the Material-UI code) a blur occurs when you click on an option and the list box closes (which also prevents the drag from starting).

Here's a sandbox that allows onDragStart to be triggered by stopping propagation of the mouse down event and forcing the Autocomplete to stay in an open state (open={true}). I'm not recommending this as a course of action since it causes the Autocomplete to behave strangely, but it at least demonstrates what obstacles would need to be overcome to get drag to work. I don't think there will be any easy way to get drag to work without disrupting the Autocomplete's functionality.

Related