simple-react-cytoscape
Version:
Simple container for Cytoscape in React Apps
41 lines (38 loc) • 1.26 kB
JavaScript
import { jsx } from 'react/jsx-runtime';
import { useState, useMemo, useEffect } from 'react';
import cytoscape from 'cytoscape';
/**
* Generate unique IDs for each
* cytoscape container in the app
*/
const nextId = (() => {
let id = 0;
return () => {
id += 1;
return `simple-react-cytoscape-${id}`;
};
})();
const SimpleReactCytoscape = ({ options, cyCallback: getCy, }) => {
const [cy, setCy] = useState();
const id = useMemo(nextId, []);
useEffect(() => {
if (!cy) {
let container;
try {
container = document.getElementById(id) || undefined;
}
catch (e) {
// Might be running Headless (the unit test are headless)
container = undefined;
}
const newCy = cytoscape(Object.assign(Object.assign({}, options), { container }));
setCy(newCy);
// If a callback was supplied we can now return the value
if (getCy) {
getCy(newCy);
}
}
}, [cy, getCy, id, options]);
return jsx("div", { id: id, className: "simple-react-cytoscape" }, void 0);
};
export { SimpleReactCytoscape };