nx-react-sigma
v1.4.2
Published
A powerful React wrapper for Sigma.js that provides interactive graph visualizations with advanced layout management and user interactions
Downloads
23
Readme
nx-react-sigma
A modern, high-performance React wrapper for Sigma.js v3 built with Clean Architecture principles. It provides a type-safe, modular interface for creating advanced interactive graph visualizations.
🚀 Why nx-react-sigma?
- Clean Architecture: Built with clear separation of concerns (Domain, Application, Infrastructure layers), making it robust and maintainable.
- Performance First: Frequent updates (like node positions) are handled via
use-context-selectorto minimize React re-renders, ensuring 60fps performance even with large graphs. - Type Safety: Written in TypeScript with complete type definitions.
- Rich Interactions: Out-of-the-box support for drag-and-drop, hover, click, and zoom interactions.
- Layout Management: Integrated support for Force, ForceAtlas2, Noverlap, and custom layouts like Tree and Community layouts.
- Batteries Included: Graph visualization dependencies (sigma, graphology, layouts) are bundled - just install and use.
📦 Installation
npm install nx-react-sigma
# or
pnpm add nx-react-sigma
# or
yarn add nx-react-sigmaPeer Dependencies
Only React is required as a peer dependency:
{
"react": ">=18.3.1",
"react-dom": ">=18.3.1"
}Note: All graph visualization dependencies (sigma, graphology, layout libraries, chroma-js) are bundled with the package.
🎯 Quick Start
Basic Usage
import React from 'react';
import { MultiDirectedGraph } from 'graphology';
import { SigmaContainer } from 'nx-react-sigma';
import 'nx-react-sigma/style.css'; // Don't forget styles!
// Setup graph
const graph = new MultiDirectedGraph();
graph.addNode('A', { x: 0, y: 0, size: 10, color: '#FA4F40', label: 'Node A' });
graph.addNode('B', { x: 100, y: 100, size: 10, color: '#727EEA', label: 'Node B' });
graph.addEdge('A', 'B', { size: 2, color: '#ccc' });
function App() {
return (
<div style={{ height: '500px', width: '100%' }}>
<SigmaContainer graph={graph}>{/* Children can access sigma context */}</SigmaContainer>
</div>
);
}Advanced Usage with Interactions & Layouts
To use hooks, your components must be children of SigmaContainer.
import { useEffect } from 'react';
import {
SigmaContainer,
useDnDInteraction,
useClickNode,
useLayoutForce,
useSigmaRestart,
} from 'nx-react-sigma';
const GraphInteractions = () => {
// 1. Enable Drag and Drop
useDnDInteraction();
// 2. Handle Node Clicks
useClickNode((node, event) => {
console.log('Clicked node:', node);
});
// 3. Apply Force Layout
const layout = useLayoutForce({
settings: { attraction: 0.0005, repulsion: 0.1 },
});
// Start layout on mount
useEffect(() => {
layout?.start();
return () => layout?.stop();
}, [layout]);
return null;
};
export default function App({ graph }) {
return (
<SigmaContainer graph={graph}>
<GraphInteractions />
</SigmaContainer>
);
}📚 API Reference
Core Components
SigmaContainer
The root provider component.
| Prop | Type | Default | Description |
| ------------------ | ------------------- | ------------ | ------------------------------------------------- |
| graph | Graph | Required | The graphology instance. |
| settings | Partial<Settings> | {} | Sigma.js settings object. |
| layoutTimeoutMil | number | 2000 | Timeout in ms for layouts to auto-stop if needed. |
| id | string | undefined | DOM ID for container. |
| className | string | undefined | CSS class for container. |
Settings Example
import { SigmaContainer, drawLabel, drawHover } from 'nx-react-sigma';
const sigmaSettings = {
// Rendering
renderLabels: true,
renderEdgeLabels: false,
defaultNodeColor: '#999',
defaultEdgeColor: '#ccc',
// Node sizing
minNodeSize: 3,
maxNodeSize: 15,
// Edge sizing
minEdgeSize: 1,
maxEdgeSize: 5,
// Label rendering
labelFont: 'Inter, sans-serif',
labelSize: 12,
labelWeight: '500',
labelColor: { color: '#333' },
// Custom renderers (optional)
labelRenderer: drawLabel,
hoverRenderer: drawHover,
// Performance
hideLabelsOnMove: true,
hideEdgesOnMove: false,
// Interaction
enableEdgeEvents: true,
zoomToSizeRatioFunction: (ratio) => Math.pow(ratio, 0.5),
};
function App({ graph }) {
return (
<div style={{ height: '100vh', width: '100%' }}>
<SigmaContainer graph={graph} settings={sigmaSettings}>
{/* Children */}
</SigmaContainer>
</div>
);
}Hooks
Core Context
useSigma(): Get theSigmainstance.useGraph(): Get theGraphologygraph instance.useLayoutManager(): Access the layout manager singleton.useGraphManager(): Access the graph manager (for commands/history).
Interactions
useDnDInteraction(): Enables drag and drop for nodes.useClickNode(callback?): Register a callback for node click events.useEdgeNodeHoverInteraction(): Handles hover states for nodes and edges (highlighting).useZoomToNode(): Returns a function(nodeId: string) => voidto fly to a node.useZoomToNodes(): Returns a function(nodeIds: string[]) => voidto fit view to multiple nodes.useSigmaRestart(): Returns a function to refresh the sigma renderer.useRegisterInteractionsEvent(event, callback): Low-level hook to register any sigma event.
Layouts
useLayoutForce(settings): Usesgraphology-layout-force.useLayoutForceAtlas2(settings): Usesgraphology-layout-forceatlas2.useLayoutNoverlap(settings): Usesgraphology-layout-noverlap.useIndexParallelEdges(): Automatically indexes parallel edges to render them as curves.
Query
useQuery(): Hook to run graph pathfinding/traversal queries.
Graph Management & History
The package implements a Command Pattern for graph mutations, allowing simple Undo/Redo.
const graphManager = useGraphManager();
const cmdHistory = graphManager.getCommandHistory();
// Execute a command
graphManager.getCommandManager().execute('addNode', {
key: 'node-1',
attributes: { x: 0, y: 0, size: 10 },
});
// Undo
cmdHistory.undo();
// Redo
cmdHistory.redo();Available Commands: addNode, removeNode, addEdge, removeEdge, updateNodeAttributes, updateEdgeAttributes, removeAllNodes.
Helpers & Rendering
Import these from nx-react-sigma for custom rendering:
drawLabel: Default label renderer.drawHover: Default hover renderer.drawEdgeLabel: Default edge label renderer.
Specialized Layouts
Classes available for complex layout needs:
TreeLayout: For hierarchical structures.ForceAtlas2CommunityLayout: Specialized layout respecting community clusters.
🎨 Styling
The core styles are minimal but necessary for the container and canvas sizing.
/* Import in your root file */
@import 'nx-react-sigma/style.css';Usually, you will want to containerize the component with a fixed height:
<div style={{ width: '100%', height: '800px' }}>
<SigmaContainer graph={graph} />
</div>🏗️ Architecture
nx-react-sigma/
├── lib/
│ ├── components/ # React Components (SigmaContainer)
│ ├── contexts/ # Context Providers (Sigma, Graph)
│ ├── use-cases/ # Business Logic Hooks (Interactions, Layouts)
│ ├── entities/ # TypeScript Interfaces & Models
│ ├── graphology/ # Graph Algorithms, Commands & Adapters
│ ├── helpers/ # Canvas Rendering Helpers
│ └── main.ts # Public API exports
└── dist/ # Compiled output📄 License
ISC
Built with ❤️ by the nx-graph-platform team.
