Reputation: 301
I am trying to develop a project that uses Cytoscape using React Component. I tried to follow the documentation from - https://github.com/plotly/react-cytoscapejs and tried to access the cy
object to use the Cytoscape API.
This is the code I wrote,
import CytoscapeComponent from "react-cytoscapejs";
function App() {
const [elements, setElements] = useState([
{ data: { id: "a" } },
{ data: { id: "b" } },
{ data: { id: "c" } },
{ data: { id: "d" } },
{ data: { id: "e" } },
{ data: { id: "f" } },
// edges
{
data: {
id: "ab",
source: "a",
target: "b",
},
},
{
data: {
id: "cd",
source: "c",
target: "d",
},
},
{
data: {
id: "ef",
source: "e",
target: "f",
},
},
{
data: {
id: "ac",
source: "a",
target: "c",
},
},
{
data: {
id: "be",
source: "b",
target: "e",
},
},
]);
return (
<div className="App">
<button onClick={()=>setElements(...elements,[{ data: { id: "x" } },])}>Add</button>
<CytoscapeComponent
cy={(cy) => {
cy.add(elements);
console.log(cy);
}}
style={{ width: "100vw", height: "100vh" }}
/>
;
</div>
);
}
export default App;
This creates the graph but when I click on the Add button, then the screen becomes blank. On inspecting the console, I get cytoscape.cjs.js:831 Uncaught Error: Can not create second element with ID a
Upvotes: 1
Views: 1133
Reputation: 461
You got the state updating function wrong.
Try this,
<button onClick={()=>setElements(prev => [...prev, { data: { id: 'x' } }])>Add</button>
Upvotes: 1