Search code examples
javascriptreactjsvis.jsreact-graph-vis

React: how to access component function from a click event on vis.js edge?


I have a react component, like:

export default class App extends Component {
  // ...

  _openDialog = () => {
    this.setState({ isDialogOpen: true });
  };

  render() {
    return (
      <div>
        <div className="tree_graph_div">
          <Graph
            graph={graph}
            events={{
              selectEdge: function(event) {
                var { nodes, edges } = event;
                if (edges.length == 1) {
                  //I want to access _openDialog here with edge id
                }
              }
            }}
          />
        </div>
        <div>
          <Dialog />
        </div>
      </div>
    );
  }
}

The graph is created with react-graph-vis.

I want to make the selectEdge event to handle: open the dialog for this edge_id.

The event have the edge id, but how I can access back to the function _openDialog?

I tried this, but this here stands for the Graph object, not the App.

Thanks


I tried change Graph to this with arrow function:

<Graph graph={graph}
  events={{
    selectEdge: (event) => {
      debugger;
    }
  }}
/>

But by stop in debugger point, the "this" doesn't have the function _openDialog.


Solution

  • You can change the function given to selectEdge to an arrow function to use the enclosing lexical scope instead, which has _openDialog on this.

    export default class App extends Component {
      // ...
    
      render() {
        return (
          <div>
            <div className="tree_graph_div">
              <Graph
                graph={graph}
                events={{
                  selectEdge: (event) => {
                    var { nodes, edges } = event;
                    if (edges.length == 1) {
                      this._openDialog(edges);
                    }
                  }
                }}
              />
            </div>
            <div>
              <Dialog />
            </div>
          </div>
        );
      }
    }