react-sigma

repository·master·Indexed 42 days ago

https://github.com/dunnock/react-sigma

A lightweight React wrapper for the Sigma.js library used to draw and explore network graphs. It allows for graph configuration using JSX and supports asynchronous loading via components like LoadJSON, LoadGEXF, and NeoCypher. Version 1.2.35 supports canvas, WebGL, and SVG rendering, as well as layout plugins such as ForceAtlas2, ForceLink, and NOverlap.

Tokens
11.1K
Snippets
40
Records
58
Agent score
51%

What's inside react-sigma

  1. Create custom sigma-aware components

    master

    The Sigma container mounts any child component with the sigma instance available under props.sigma. You can use this to write components that interact directly with the graph instance.

    class MyCustomSigma extends React.Component {
      constructor(props) {
        super(props)
        // Access the sigma instance via props.sigma
        props.sigma.graph.addNode({id:"n3", label:props.label})
      }
      render() { return null; }
    }
    
    // Usage:
    <Sigma>
      <MyCustomSigma label="Label" />
    </Sigma>
  2. How asynchronous component composition works

    master

    Components that initialize or provide graph changes asynchronously (like LoadJSON) are designed to mount their children only after initialization is complete. This allows for sequential composition in pure JSX without needing manual callbacks or handlers. For example, a RelativeSize component placed inside a LoadJSON component will only be instantiated once the JSON file has been successfully loaded.

    <Sigma>
      <LoadJSON url="/arctic.json">
        <RelativeSize initialSize={8}/>
      </LoadJSON>
    </Sigma>
  3. Install react-sigma

    master

    You can install react-sigma using npm, yarn, or bower. For environments without a bundler like webpack or browserify, you can reference the single file distribution via unpkg, which makes the library available under the global variable ReactSigma.

    npm install --save react-sigma
    
    # or
    
    yarn add react-sigma
    
    # or
    
    bower install https://unpkg.com/react-sigma@1.2/dist/react-sigma.min.js
  4. Enable Flow type checking

    master

    The project uses Flow for type checking. To enable it, you must have flow-typed installed globally. Custom types are located within component files (props and state descriptions) and in the /types/ subdirectory.

    npm install -g flow-typed
    flow-typed
  5. Minimize bundle size with webpack2 or rollup

    master

    When using bundlers like webpack2 or rollup, you can minimize your bundle size by importing only the specific components you need. Unused components will be tree-shaken and excluded from the resulting bundle.

    import { Sigma, ForceAtlas2 } from 'react-sigma'
  6. Handle Sigma events

    master

    Event handlers passed to the Sigma component (like onClickNode or onOverEdge) receive a Sigma$Event object. This object contains data about the specific node or edge involved and the event captor information.

    type Sigma$Event = {
      data: {
        node?: Sigma$Node,    // Present during node events
        edge?: Sigma$Edge,    // Present during edge events
        captor: {
          clientX: number,
          clientY: number
        }
      }
    }
  7. Use the ForceAtlas2 component for graph layout

    master

    The ForceAtlas2 component is a React wrapper for the ForceAtlas2 sigma.js layout plugin. It automatically starts the layout algorithm when the component is mounted.

    Important Requirements:

    • The sigma instance must be provided via the sigma prop.
    • The component assumes the sigma graph is already initialized and available. It should be mounted within a Sigma component (if the graph is preloaded) or within a loader component (like NeoCypher).
    • When the layout finishes (based on the timeout prop), the component updates its internal state to stop the running animation.

    Lifecycle Behavior:

    • Mounting: Starts the ForceAtlas2 algorithm using the provided configuration.
    • Unmounting: Automatically calls sigma.killForceAtlas2() and clears any active timers to prevent memory leaks.
    • Edge Rendering: If the graph contains more than 1000 edges, the component automatically sets drawEdges to false in the sigma settings to maintain performance.
    <ForceAtlas2 
      sigma={sigmaInstance} 
      worker={true} 
      gravity={1.0} 
      timeout={5000}
    />
  8. Implement a custom layout plugin using ReactSigmaLayoutPlugin

    master

    To create a custom layout plugin in react-sigma, extend or wrap the ReactSigmaLayoutPlugin component. This base class manages the lifecycle of a sigma layout by automatically calling start() on mount, stop() on unmount, and re-initializing the layout when props change.

    To use it, you must provide the following props:

    • sigma: The sigma instance.
    • start: A function that initiates the layout and returns a Sigma$Listener.
    • config: A function that accepts a configuration object (derived from the remaining props) and returns a Sigma$Listener.
    • stop: A function to stop the layout.

    Any additional props passed to your component (other than sigma, start, stop, config, or children) are automatically stripped and passed to the config function as the layout configuration object.

    const NOverlap = (props: Props) => {
      const s = props.sigma
      if (s) return (
        <ReactSigmaLayoutPlugin
          start={() => s.startNoverlap()}
          config={(options) => s.configNoverlap(options)}
          stop={() => s.stopNoverlap()}
          {...props} 
        />
      )
      return null
    }
    
    // Usage in a component tree:
    <NOverlap easing="cubicInOut" />
  9. Render a graph with an embedded graph object

    master

    To render a graph defined directly in your code, use the Sigma component and pass your graph object to the graph prop.

    Important: Graph nodes require x, y, and size properties to be displayed. You can use plugins like RelativeSize and RandomizeNodePositions to automatically generate these properties. If you want to keep track of node positions (as Sigma updates them), set settings={{ clone: false }}.

    import {Sigma, RandomizeNodePositions, RelativeSize} from 'react-sigma';
    
    let myGraph = {
      nodes:[{id:"n1", label:"Alice"}, {id:"n2", label:"Rabbit"}], 
      edges:[{id:"e1", source:"n1", target:"n2", label:"SEES"}]
    };
    
    // In your render method:
    <Sigma graph={myGraph} settings={{drawEdges: true, clone: false}}>
      <RelativeSize initialSize={15}/>
      <RandomizeNodePositions/>
    </Sigma>
  10. Load a graph from an external JSON file

    master

    Use the LoadJSON component inside a Sigma component to load graph data from a specific path asynchronously.

    import {Sigma, LoadJSON} from 'react-sigma'
    
    // In your render method:
    <Sigma style={{width:"200px", height:"200px"}}>
      <LoadJSON path="/public/data.json" />
    </Sigma>