I am trying to do something similar, but I'm using a third party library (Apollo) that uses React Hooks and was giving errors when used within a class component, so I switched to a function component. (I think this has something to do with class components not having hooks, but the Apollo hooks are used in a function called from the component itself, so I'm not quite sure how it all fits together.)
Using refs with function components is a bit different. I think there is a way to do it using the useEffect
hook, but in my particular use case I was having an issue with the hook firing before render (because the hook was set up to fire when the data changed, which was dynamic) and the reference still not being available.
To get around this, a solution appears to be to use the useCallback
hook, which gets fired when the reference is attached to/detached from a node. I basically took it from here, which describes a situation with a similar precondition: https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node
I just implemented it so I haven't had any time to figure out exactly what's going on and what will happen at later points, but the way it's set up below should cause it to trigger whenever data
changes (because it's in the dependency list [data]
passed to useCallback
). Obviously in this example that's not going to happen but I figured I'd leave it in.
Note that this has been modified from my specific example and I haven't actually run the code below, so there may be some errors but I think it should point others in the right direction.
I'm really new to React so I'm not remotely confident that this is the most appropriate/best/most idiomatic way to solve this problem, so if anyone has any additional input, I'd love to hear it.
import { DataSet, Network } from 'vis';
import React, { Component, createRef } from "react";
const nodes = new DataSet([
{ id: 1, label: 'Node 1' },
{ id: 2, label: 'Node 2' },
{ id: 3, label: 'Node 3' },
{ id: 4, label: 'Node 4' },
{ id: 5, label: 'Node 5' }
]);
// create an array with edges
const edges = new DataSet([
{ from: 1, to: 3 },
{ from: 1, to: 2 },
{ from: 2, to: 4 },
{ from: 2, to: 5 }
]);
const data = {
nodes: nodes,
edges: edges
};
const options = {};
// initialize your network!
const VisNetwork = () => {
const triggeredRef = React.useCallback( node => {
if ( node === null )
return;
const network = new Network(node, data, options);
}, [data]);
render() {
return (
<div ref={triggeredRef} />
);
}
}