I’m trying to add a help icon inside a Select component, and would like to do something like this:
<Select
onChange={event => {
...
}}
value={mode}
variant='outlined'
>
{modes.map(m => (
<MenuItem
key={m.key}
value={m.value}
>
{m.label}
<IconButton
onClick={() => {
alert('Clicked!')
}}
>
<HelpIcon />
</IconButton>
</MenuItem>
))}
</Select>
I.e. I want to open the dropdown like normal when clicking the label and also be able to capture the click on the IconButton. What happens with the above code is whenever I click the IconButton, the onClick is not fired (i.e. the alert(‘Clicked!’) is not called), and the Select dropdown opens.
Is there any way to prevent clicks on the IconButton from opening the dropdown, and only be handled by IconButton’s onClick ?
See minimal example here: https://codesandbox.io/s/select-onclick-on-menuitems-button-gedusv
2
Answers
A solution that seems to work is to rather handle the mouseDown event:
Not sure if this is the best solution, but seems like it does the trick
You will need to use
event.stopPropagation()
to stop the click event from the IconButton from bubbling up and triggering the change event of your Select component.