Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

246
Views
How to add elements in cytoscape graph from react component?

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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You got the state updating function wrong.
Try this,

<button onClick={()=>setElements(prev => [...prev, { data: { id: 'x' } }])>Add</button>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!