I have a TreeView component that I render next to an Options component that holds to buttons.
return (
<div
style={{ display: "flex", flexDirection: "column", height: "100%" }}
>
<Options />
<div
onClick={stopPropagation}
>
<ThemeProvider theme={fontMuiTreeView}>
<TreeView
aria-label="rich object"
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpandIcon={<ChevronRightIcon />}
expanded={expandedNodes}
onClick={clearSelection}
onNodeToggle={handleToggle}
onNodeSelect={onSelect}
sx={{ height: "90vh", overflowY: 'scroll' }}
>
{treeData.map((node) => renderTree(node))}
</TreeView>
</ThemeProvider>
</div>
</div>
);
Options component looking like this:
const Options = () => {
if (editable) {
return (
<div
style={{
display: "flex",
justifyContent: "center",
color: "white",
margin: "4px 4px",
marginTop: "20px",
marginBottom: "25px",}}>
<Space>
<Button
style={{ color: "#fff", borderColor: "#192D40", backgroundColor: "#1890ff", cursor: "pointer" }}
onClick={onNewEntity}
>Add Entity</Button>
<Button
style={{ color: "#fff", borderColor: "#192D40", backgroundColor: "#1890ff", cursor: "pointer"}}
onClick={onNewScenario}
>Add Scenario</Button>
</Space>
</div>
);
} else {
return null;
}
};
My problem is that - when I try to add a new entity using my entity button I have to click it twice if I have already highlighted one of the TreeItems in the TreeView. If I haven't highlighted anything yet the TreeItems (entities) are added, as supposed, when clicking the button. I believe the problem is due to the fact that the TreeItem is highlighted after a click and when pressing outside of the TreeView, one of the buttons, or anywhere else, clears this highlight. When the highlight is cleared the button works as expected.
I've been trying to use stopPropagation, pessist, preventDefault on the TreeItem. I've also searched for a solution that would prevent the TreeItem being highlighted in the first place.
I fixed the issue by letting the options element be a part of the TreeView. When doing this - they are part of the some propogation/bubling and it makes the options elements get the same events.