Reputation: 13
I am implementing material ui tabs with close functionality. On the close tab not able to set the active tab value in the current tab. its giving warning error.
code in the codesandbox
Upvotes: 1
Views: 4790
Reputation: 5288
When clicking the close icon, you're not only executing handleClose
but also the handleChange
function. This happens because of the principle called event bubbling.
When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.
Source: javascript.info
--
To fix your issue, you have to stop the event propagation on close icon's click event. Modify your handleClose
to
const handleClose = useCallback(
(event, tabToDelete) => {
// stop event from propagating to the target element's parent
event.stopPropagation();
const tabToDeleteIndex = activetabs.findIndex(
tab => tab.id === tabToDelete.id
);
const updatedTabs = activetabs.filter((tab, index) => {
return index !== tabToDeleteIndex;
});
const previousTab =
activetabs[tabToDeleteIndex - 1] ||
activetabs[tabToDeleteIndex + 1] ||
{};
setActiveTabs(updatedTabs);
setActiveTab(previousTab.id);
},
[activetabs]
);
...now you call that using
<a
className="closeTab"
title={"Close tab"}
onClick={(event) => handleClose(event, tab)}
>
<CloseIcon />
</a>
PS: If you want to use IconButton
component instead of a
tag, use
<IconButton component="div" onClick={(event) => handleClose(event, tab)}>
<CloseIcon />
</IconButton>
that will avoid you from getting the error from material-ui, which you might have already encountered.
Warning: validateDOMNesting(...): <button> cannot appear as a descendant of <button>.
Upvotes: 8