question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Question] setting elements property via setState causes graph nodes to stack on top of each other

See original GitHub issue

I have a simple react app that makes a REST GET call and uses the result to display a few nodes. However, all the nodes end up stacked on top of each other at the top left corner. Apologies in advance as I’m a web newbie.

import React, {Component} from 'react';
import Cytoscape from 'cytoscape';
import './App.css';
import CytoscapeComponent from 'react-cytoscapejs';
import cola from 'cytoscape-cola';
import Pace from 'react-pace-progress';

Cytoscape.use(cola);

class App extends Component {

    constructor(props) {
        super(props);
        this.state = {
            isLoading: true,
            graph: [],
            elements: [],
        };
    }

    render() {
        const layout = {
            name: 'cola',
            padding: 50
        }
        return (
            <div>
                {this.state.isLoading ? <Pace color="#27ae60"/> :
                    <CytoscapeComponent elements={this.state.elements} layout={layout}
                                        style={{position: 'absolute', width: '100%', height: '100%'}}/>}

            </div>
        );
    }

    componentDidMount() {

        fetch(`http://127.0.0.1:5000/jil/all`)
            .then(response => response.json())
            .then(result => this.setState({elements: this.buildJobGraph(result)}))

        this.setState({isLoading: false});
        
    }

    buildJobGraph(items) {
        let jobGraph = [];
        items.forEach(e => {
            if (e['type'] === 'box') {
                jobGraph.push(
                    {
                        data: {'id': e['name'], 'label': e['name']},
                        style: {'shape': 'rectangle', width: '280px', 'text-valign': 'center', 'text-halign': 'center'}
                    }
                );
            }
        });
        console.log(jobGraph);
        return jobGraph;
    }

    /*sleep = (milliseconds) => {
        return new Promise(resolve => setTimeout(resolve, milliseconds))
    }*/
}

export default App;

And this is what I end up with:

image

I then have to drag the items to the middle and spread them out:

image

I believe the cola layout is not taking effect. Any help you can give me would be immensely appreciated.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
kstewart83commented, Jun 19, 2019

I was having a similar issue. Per the Cytoscape Documentation, the new layout needs to be created and run when the elements have been updated. Not sure this is exposed through the React side of things, but it is easy to get the original Cytoscape object. So in my component code I have something like:

componentWillUpdate = () => {
    if(this.cy) {
      var layout = this.cy.layout({name: 'cose-bilkent'})
      layout.run();
    }
  }

And the element looks like this:

<CytoscapeComponent 
          elements={this.state.elements} 
          style={{ width: '100vw', height: '85vh', backgroundColor: 'rgb(250, 250, 250)' }}
          layout={{name: 'cose-bilkent'}}
          cy={(cy:any) => (this.cy = cy)}
 />

That seems to work.

0reactions
mariela-plazacommented, Sep 30, 2022

You have no positions defined on the nodes so they default to (0,0)

The actual cytoscape supports without even passing position. Isnt that supported in the react version?

I am currently having the same issue. So far I’ve been using only the cytoscape.js library and it has worked great. I haven’t had to define position on the nodes for the graph to work correctly.

What I don’t understand is why we don’t have to define positions for the nodes when we are not fetching the data but when we do we have to define them.

This project is working perfectly without fetching data but as soon as I try to make something similar but fetching the data from an API and then doing the mapping myself, the whole Cytoscape Graph becomes messy.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Alter react component state properly - Stack Overflow
I created a live example at stackblitz which isn't working yet caused by other failures I make and can't find. The components I...
Read more >
Reconciliation - React
When building up a new tree, new DOM nodes are inserted into the DOM. Component instances receive UNSAFE_componentWillMount() and then componentDidMount() . Any ......
Read more >
Top 50 React Interview Questions and Answers in 2023
Here are the Top React Interview Questions which an aspiring front end developer must prepare in 2023 for React interviews.
Read more >
How re-render a component without using setState() method ...
Method 1 (by changing props): If we pass the state of the parent component as a prop to the child and call setState...
Read more >
Untitled
Javascript Cannot Read Property Of Undefined See more in the Marketplace. ... 2019 · Top 100 important question for React developer interview for...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found