I am working with Cytoscape.js and React. I have a functional GraphComponent that receives the list of elements used to render the Cytoscape graph, and a list of nodes I wish to animate.
The problem I have is that I cannot figure out how to persist the 'cy' object so that I may access it at a later time. Specifically, I would like to add a class to the nodes in path.
const MyComponent = ({ myElements, path }) => {
useEffect(() => {
const cy = {
...
elements: myElements
...
}
}, []);
useEffect(() => {
// This fails since 'cy' is undefined
cy.$id("A").addClass("highlighted");
}, [path]);
return (
<div id="cy" />
);
}
Idea #1: Create a variable 'cy' that I can then set the value to in useEffect.
Problem: After the initial render the value of 'cy' is lost
const MyComponent = ({ myElements, path }) => {
let cy;
useEffect(() => {
cy = {
...
elements: myElements
...
}
}, []);
useEffect(() => {
// This fails since 'cy' is undefined
cy.$id("A").addClass("highlighted");
}, [path]);
return (
<div id="cy" />
);
}
Idea #2: Save cy as state.
Problem: Cy is not properly initialized
const MyComponent = ({ myElements, path }) => {
const [cy, setCy] = useState({});
useEffect(() => {
setCy({
...
elements: myProp
...
});
}, []);
useEffect(() => {
cy.$id("A").addClass("highlighted");
}, [path]);
return (
// This fails since cy is not initialized to a cytoscape object when component mounts
<div id="cy" />
);
}
So the question is, how do I create and access the cytoscape object (and modify its nodes and elements) inside a react functional component?