I'm trying to create a conditional collapse that prevents certain elements within the header from toggling the collapse. For example, I have a delete button within the toggle element, but I don't want it to activate the toggle.
I tried:
const handleToggle = (e, id) => {
if(!e.target.classList.contains('remove-btn')) {
if (isOpen === id) {
setIsOpen('');
} else {
setIsOpen(id);
}
}
};
and also using the e.target.name:
if(e.target.name !== 'remove-btn') {<allow toggle>}
And this is the toggle within the return:
<ListGroupItem
onClick={() => handleToggle(id)}>
<Button
className='remove-btn'
name='remove-btn'
onClick={() => handleDelete(id)}>
×
</Button>
{name}
</ListGroupItem>
<Collapse>...</Collapse>
If I click anywhere on the ListGroupItem, it should toggle the collapse, unless I click on the delete Button, which should only run the handleDelete function, and not toggle the collapse.
I know that the delete is eventually going to remove the whole element anyway, but I also have an input that is toggling the collapse and I don't want it to. Thanks for helping me understand this!
I found a similar question with a two possible solutions, but I'm wondering if there is a better answer.
I used 95faf8e76605e973's answer to this question, and simply added the e.stopPropagation() function to the appropriate onClicks.
<ListGroupItem
onClick={() => handleToggle(id)}>
<Button
className='remove-btn'
name='remove-btn'
onClick={(e) => {
e.stopPropagation();
handleDelete(id);
}}>
×
</Button>
{name}
</ListGroupItem>