Search code examples
reactjsgraphviz

React click events on flowchart nodes in graphviz-react?


I'm trying out a few different methods for rendering flowcharts in React. So far I've gotten mermaid and react-flow working, and now I'm working on graphviz.

With mermaid, I could just add click {nodeId} handleNodeClick to each node to get it to capture node clicks, and with react-flow I could just add onNodeClick = {handleNodeClick} to the props of ReactFlow to capture node clicks.

However, I can't find any sort of comparable functionality in graphviz-react. I can use the graphviz attributes to add a URL to each node, that will open when the node is clicked (https://graphviz.org/docs/attrs/URL/), but that is the only click-related functionality I can find, and I suspect that using a link to update the js app is the wrong way to go.

Any suggestions? I'm guessing the solution involves adding an onclick attribute to each node as a sort of post-process step, but I don't know how to do that in React.


Solution

  • figured it out. I added a useEffect(), which is effectively post-processing on the element, to go through and add the onclick event everywhere I want it, like this:

      useEffect(() => {
        const graphElement = document.querySelector('div.flowchart');
    
        flowData.forEach((item) => {
            var e = graphElement.querySelector('#'+item.id);
            if(e) {
                e.onclick= function() { 
                    SelectItemById(item.id); 
                };
            }
        });
      });
    

    on the downside, this is SUPER SLOW, and I'm wondering if there's a better way to do it...