I want to use Vis.js in a React based project. Since none of the Vis Network implementations work for me I have to use the plain library.
This is my test React component
import { DataSet, Network } from 'vis';
import React, { Component, createRef } from "react";
class VisNetwork extends Component {
constructor() {
super();
this.network = {};
this.appRef = createRef();
this.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' }
]);
this.edges = new DataSet([
{ from: 1, to: 3 },
{ from: 1, to: 2 },
{ from: 2, to: 4 },
{ from: 2, to: 5 }
]);
this.data = {
nodes: this.nodes,
edges: this.edges
};
this.options ={};
}
componentDidMount() {
this.network = new Network(this.appRef.current, this.data, this.options);
}
render() {
return (
<div ref={this.appRef} />
);
}
}
export default VisNetwork;
It's the only component mounted so far
ReactDOM.render(<VisNetwork />,document.getElementById('mynetwork'));
My question is how I can access the properties of the network, for example, to get or delete a node.
node = nodes.get(nodeId);
I read about React Ref and tried something like
() =>{ console.log(document.getElementsByClassName('vis-network'))
as callback of ReactDOM.render()
but that doesn't help.
Another question is why isn't the ref not set and it's just <div>
.
Because I thought that this.appRef = createRef();
in the constructor of the component and ref={this.appRef}
in render() would lead to a ref.
I hope you can give me a hint.
Actually the flow should be the other way round, define the nodes outside of the component, then pass them in. For that define the constructor as:
constructor(props) {
super(props);
this.nodes = props.nodes;
//...
}
Then construct it as:
const nodes = new DataSet([/*...*/]);
ReactDOM.render(<VisNetwork nodes={nodes} />,document.getElementById('mynetwork'));
Note that you should put anything stateful into this.state
and use setState
to mutate it.