plotly / react-cytoscapejs

React component for Cytoscape.js network visualisations
MIT License
477 stars 68 forks source link

Error with 'window' while server side rendering #55

Closed anirudhjain75 closed 4 years ago

anirudhjain75 commented 4 years ago

When using react-cytoscape with gatsby app. It works while testing locally but has issues when used with gatsby cloud due to server side rendering.

mikolasan commented 2 years ago

That's very rude to close the issue without any explanation, besides having the correct title. Nevertheless there is another issue #69, but that one also has only vague allusions on how to fix it. So I don't know how that can be helpful either. Luckily I found a clue in this pull request #89.

The workaround. Make the component and all module imports conditional to the window object. Here is the code:

import React from 'react';

const YourComponent = () => {
  const elements = ...;
  const layout = {
    name: 'klay',
  };
  const stylesheet = ...;
  const style = ...;

  let CytoscapeComponent
  if (typeof window !== 'undefined') {
    CytoscapeComponent = require('react-cytoscapejs');
    const Cytoscape = require('cytoscape');
    // const COSEBilkent = require('cytoscape-cose-bilkent');
    const Klay = require('cytoscape-klay');
    Cytoscape.use(Klay)
  } else {
    CytoscapeComponent = () => (<></>)
  }

  return (
    <CytoscapeComponent
      elements={elements}
      layout={layout}
      stylesheet={stylesheet}
      style={style}
    />
  )
}

export default YourComponent