react-cytoscapejs

repository·master·Indexed 19 days ago

https://github.com/plotly/react-cytoscapejs

A React wrapper for the Cytoscape.js library (version 2.0.0) that enables the rendering and interaction of complex network graphs within React applications. It provides the CytoscapeComponent for managing graph elements, stylesheets, and layouts, along with props to control viewport interactivity, zooming, panning, and headless rendering modes.

Tokens
3.3K
Snippets
10
Records
13
Agent score
69%

What's inside react-cytoscapejs

  1. Install react-cytoscapejs and cytoscape

    master

    To use react-cytoscapejs, you must also install cytoscape. It is recommended to specify a version of cytoscape (3.2.19 or newer) to ensure compatibility with the expected semver range.

    # Using npm
    npm install react-cytoscapejs
    npm install cytoscape@3.x.y
    
    # Using yarn
    yarn add react-cytoscapejs
    yarn add cytoscape@3.x.y
  2. Basic usage of CytoscapeComponent

    master

    The CytoscapeComponent is used within a React component's render method to display a graph. It requires an elements prop (a list of nodes and edges) and a style prop to define the container dimensions.

    import React from 'react';
    import ReactDOM from 'react-dom';
    import CytoscapeComponent from 'react-cytoscapejs';
    
    class MyApp extends React.Component {
      render() {
        const elements = [
           { data: { id: 'one', label: 'Node 1' }, position: { x: 0, y: 0 } },
           { data: { id: 'two', label: 'Node 2' }, position: { x: 100, y: 0 } },
           { data: { source: 'one', target: 'two', label: 'Edge from Node1 to Node2' } }
        ];
    
        return <CytoscapeComponent elements={elements} style={ { width: '600px', height: '600px' } } />;
      }
    }
    
    ReactDOM.render( React.createElement(MyApp, document.getElementById('root')));
  3. Configure graph elements

    master

    The elements prop accepts a flat list of Cytoscape elements as non-stringified JSON.

    Note: Avoid using arrays or objects inside an element's data or scratch fields unless you are using a custom diff() prop for performance.

    If your data is in the { nodes: [], edges: [] } format, use the static CytoscapeComponent.normalizeElements() method to flatten it before passing it to the component.

    <CytoscapeComponent
      elements={CytoscapeComponent.normalizeElements({
        nodes: [
          { data: { id: 'one', label: 'Node 1' }, position: { x: 0, y: 0 } },
          { data: { id: 'two', label: 'Node 2' }, position: { x: 100, y: 0 } }
        ],
        edges: [
          {
            data: { source: 'one', target: 'two', label: 'Edge from Node1 to Node2' }
          }
        ]
      })}
    />
  4. Access the Cytoscape instance via the cy prop

    master

    The cy prop allows you to obtain a direct reference to the underlying Cytoscape instance using a React ref function. This is useful for calling the Cytoscape API directly for imperative operations.

    class MyApp extends React.Component {
      render() {
        return <CytoscapeComponent cy={(cy) => { this.cy = cy }}>;
      }
    }
  5. Configure custom prop types for non-JSON data

    master

    If you use non-standard data structures (like Immutable.js), you must provide custom prop handlers to help the component efficiently diff and access data.

    Required/Supported handlers:

    • get(object, key): How to retrieve a value from the object.
    • toJson(object): How to convert the object to a plain JSON object.
    • diff(objectA, objectB): How to determine if two objects are equal (used to decide when to patch Cytoscape).
    • forEach(list, iterator): How to iterate over a list.
    // Example using Immutable.js
    const get = (object, key) => {
      if (Immutable.Map.isMap(object) || Immutable.List.isList(object)) {
        return object.get(key);
      } else {
        return object[key];
      }
    }
    
    const toJson = (object) => {
      if (Immutable.isImmutable(object)) {
        return object.toJSON();
      } else {
        return object;
      }
    }
    
    const diff = (objectA, objectB) => objectA !== objectB;
    
    const forEach = (list, iterator) => list.forEach(iterator);
  6. Configure stylesheet and layout

    master

    Stylesheet

    The stylesheet prop accepts Cytoscape stylesheet rules as non-stringified JSON. Note that the prop name is stylesheet (to avoid conflict with the HTML style attribute).

    Layout

    The layout prop allows you to automatically position nodes. You can pass a layout configuration object, such as { name: 'random' }.

    To use an external layout extension, you must register it with Cytoscape.use(ExtensionName) before rendering the component.

    // Stylesheet example
    <CytoscapeComponent
      stylesheet={[
        {
          selector: 'node',
          style: {
            width: 20,
            height: 20,
            shape: 'rectangle'
          }
        }
      ]}
    />
    
    // Layout with external extension example
    import Cytoscape from 'cytoscape';
    import COSEBilkent from 'cytoscape-cose-bilkent';
    import CytoscapeComponent from 'react-cytoscapejs';
    
    Cytoscape.use(COSEBilkent);
    
    // Inside render...
    const layout = { name: 'cose-bilkent' };
    return <CytoscapeComponent elements={elements} layout={layout} />;
  7. Manipulate viewport and interactivity

    master

    You can control the graph's viewport and user interaction via several props:

    PropDescription
    panThe panning position { x, y }
    zoomThe zoom level
    panningEnabledWhether the panning position is mutable overall
    userPanningEnabledWhether panning is enabled via user gestures
    zoomingEnabledWhether the zoom level is mutable overall
    userZoomingEnabledWhether zooming is enabled via user gestures
    minZoomMinimum zoom level
    maxZoomMaximum zoom level
    boxSelectionEnabledWhether shift+click-and-drag box selection is enabled
    autoungrabifyIf true, nodes cannot be grabbed
    autolockIf true, nodes cannot be moved
    autounselectifyIf true, elements have immutable selection state
  8. Configure Cytoscape elements

    master

    The elements prop accepts a flat list of Cytoscape elements as non-stringified JSON. Each element can be a node or an edge. Nodes typically include data (with an id) and optional position. Edges include data (with source and target IDs).

    Refer to the Cytoscape JSON notation for full details.

    elements: [
      { data: { id: 'one', label: 'Node 1' }, position: { x: 0, y: 0 } },
      { data: { id: 'two', label: 'Node 2' }, position: { x: 100, y: 0 } },
      { data: { source: 'one', target: 'two', label: 'Edge from Node1 to Node2' } }
    ]
  9. Apply a layout to the graph

    master

    The layout prop allows you to automatically position nodes using Cytoscape layout algorithms. It accepts an object containing the layout configuration, such as { name: 'random' }.

    Using external layout extensions: To use an extension (like cytoscape-cose-bilkent), you must register it with the global Cytoscape object before rendering the component.

    Refer to the Cytoscape layouts documentation for available algorithms.

    import Cytoscape from 'cytoscape';
    import COSEBilkent from 'cytoscape-cose-bilkent';
    import React from 'react';
    import CytoscapeComponent from 'cytoscape-reactjs';
    
    // Register the extension globally
    Cytoscape.use(COSEBilkent);
    
    class MyApp extends React.Component {
      render() {
        const elements = [
          { data: { id: 'one', label: 'Node 1' }, position: { x: 0, y: 0 } },
          { data: { id: 'two', label: 'Node 2' }, position: { x: 100, y: 0 } },
          { data: { source: 'one', target: 'two', label: 'Edge from Node1 to Node2' } }
        ];
    
        const layout = { name: 'cose-bilkent' };
    
        return <CytoscapeComponent elements={elements} layout={layout} />;
      }
    }
  10. Import the CytoscapeComponent

    master

    The react-cytoscapejs package provides a default export named Component. This component acts as a React wrapper for the Cytoscape.js library, allowing you to render interactive graph visualizations within a React application.

    import CytoscapeComponent from 'react-cytoscapejs';
    
    // Use <CytoscapeComponent /> in your JSX
  11. Configure the Cytoscape stylesheet

    master

    The stylesheet prop accepts an array of selector objects as non-stringified JSON to define the visual appearance of elements. Each object contains a selector (e.g., 'node', 'edge', or a class) and a style object containing CSS-like properties.

    Refer to the Cytoscape style documentation for available properties.

    stylesheet: [
      {
         selector: 'node',
         style: {
           'width': 30,
           'height': 30,
           'shape': 'rectangle'
         }
      }
    ]
  12. Configure headless mode and rendering hints

    master

    These props are used for specialized rendering scenarios, such as headless (non-rendered) instances or performance optimizations.

    PropTypeDescription
    headlessbooleanIf true, the Cytoscape instance is not rendered. Cannot be changed after initialization.
    styleEnabledbooleanEnables style functionality in a headless instance. Do not set this for rendered instances.
    hideEdgesOnViewportbooleanWhether edges should be hidden during zoom and pan operations (if supported).
    textureOnViewportbooleanWhether to use a preview-based scene during zoom/pan (if supported).
    motionBlurbooleanWhether to apply a motion blur effect.
    motionBlurOpacitynumberStrength of motion blur (0 to 1).
    wheelSensitivitynumberMultiplier for wheel zooming speed. Use with caution.
    pixelRatiostring or objectThe pixel ratio for rendering (e.g., 'auto' or a positive number).