javascriptreactjsvis.jsreact-graph-vis

How do I reference a parameter from outside the component?


I have this Graph component from react-graph-vis and as you can see if it can be used to access the graph methods.

You can access the prop (in this case named network) from inside the function, but I want to do things like on click event run a method, how can I do that?

i do not know what

if you want access to vis.js network api you can set the graphState in a parent component using this property

means

here is the component:

 <Graph
      graph={graphState.graph}
      //options={options}
      events={eventsState.events}
      getNetwork={(network) => {
        //  if you want access to vis.js network api you can set the graphState in a parent component using this property

        network.setOptions({
          // options
        });
      }}
    />

Solution

  • I think it's simpler than you might think. The getNetwork is a getter method attached to the graph, and the note says to get the network and set a state with it if you want to use it. Try:

    function ReactGraphComponent() {
      const [network, setNetwork] = React.useState(null);
    
      // Here you'll have to wait for the first render to access the network state, but the way to know when it is available would be to have a React callback ready.
    
      const useNetwork = React.useCallback(() => {
        if (network) {
          // Use the network like you want, whenever you call this method
        }
      }, [network]);
    
      // If you only need to use the network once, when you get it, use React.useEffect.
      React.useEffect(() => {
        if (network) {
          // Use the network like you want, whenever the network state changes
        }
      }, [network]);
    
      return (
        <Graph
          graph={graphState.graph}
          //options={options}
          events={eventsState.events}
          getNetwork={(network) => setNetwork(network)}
        />
      )
    }
    

    Now you should have access to the network via the network state.

    Here is a somewhat challenging-to-read example, and it relates to class components and not functional components, but illustrates what should be done for setting a state. https://github.com/crubier/react-graph-vis/issues/14. If Functional components is what you're using, my example above should work, if you're using class components check the GitHub issues in the previous sentence and you should be good.

    Good luck. #SemanticArts