Omer Shlifka
Omer Shlifka

Reputation: 263

React Material-UI Chip's onDelete inside Select is not working

I followed the Chips example here, in order to render chips as the renderValue of the Select:

https://material-ui.com/components/selects/

However, when I added onDelete to the chip, in order to delete the chip in one click, I can see the close icon, but the delete event is not invoked (because the menu of Select shows).

<Select
        multiple
        value={selectedProducts}
        onChange={handleProductsSearchChange}
        renderValue={selected => (
            <div className={classes.chips}>
            {selected.map(value => (
                <Chip key={value} label={find(FAKE_PRODUCTS, {id: value}).name}
                        onDelete={() => handleDeleteSearchProduct(value)} 
                        className={classes.chip} />
                ))}
            </div>)}
        MenuProps={{ PaperProps: {
            style: {
                maxHeight: 48 * 4.5 + 8,
                width: 250,
            }
        }
}}
>
{menuItems}
</Select>

When I put the chip outside of the select, the delete event is invoked. What do you think I can do in order to prevent the behaviour of the menu opening on click?

Thank you very much!

Upvotes: 25

Views: 14685

Answers (2)

Yes it works, stop propagation in chip component

onMouseDown={(event) => {
 event.stopPropagation();
}}

for continue the focus in select can create a referency selectRef = React.createRef(); and call selectRef.current.focus(); its resets the focus to the component

Upvotes: 1

Piotr Stanisławski
Piotr Stanisławski

Reputation: 606

Select component intercepts mousedown event, so add

onMouseDown={(event) => {
  event.stopPropagation();
}}

to your Chip component.

Upvotes: 58

Related Questions