force-graph.tsx
Overview
force-graph.tsx is a React functional component that renders an interactive force-directed graph visualization using the @antv/g6 graph visualization library. It provides a dynamic and visually rich representation of nodes, edges, and combos (grouped nodes) with behaviors such as dragging, zooming, collapsing/expanding combos, and tooltips showing detailed information about graph elements.
This component is designed for integration in React applications where complex relational data needs to be visualized and explored interactively. It supports customizable node and edge styles, automatic layout, and dynamic updates based on input data.
Component: ForceGraph
Description
The ForceGraph component accepts graph data as props and renders an interactive graph visualization inside a container <div>. It handles graph initialization, rendering, and updates when the data changes. The visualization supports combos (grouped nodes), tooltips, and multiple user interactions.
Props
Prop | Type | Description |
|---|---|---|
data | any | The graph data object containing nodes and edges to visualize. Expected to have at least |
show | boolean | Controls the visibility of the graph container. When |
Internal State and Refs
containerRef(useRef<HTMLDivElement>): Reference to the container DOM element where the graph canvas is mounted.graphRef(useRef<Graph | null>): Stores the currentGraphinstance from@antv/g6to manage lifecycle and updates.
Key Hooks Used
useMemo: Processes the incoming data to build nodes and combos structure only whendatachanges, optimizing performance.useCallback: Defines therenderfunction which initializes and renders the graph; memoized to avoid unnecessary re-renders.useEffect: Calls therenderfunction wheneverdataor therendercallback changes, ensuring the graph updates accordingly.
Main Functionalities
Data Preparation (nextData)
Utilizes the imported helper
buildNodesAndCombosto transform flat node data into a hierarchical combo structure required by G6.Returns a graph data object with
nodes,edges, and combos combined.
Graph Initialization and Rendering (render function)
Creates a new
Graphinstance with the following configuration:container: the container div ref.autoFitand autoResize to adapt graph to container size.behaviors: enables drag element, drag canvas, zoom canvas, collapse-expand combos, and hover activation (degree 1 to highlight relations).plugins: adds a tooltip plugin with customized content based on hovered elements (nodes, combos, edges).layout: usescombo-combinedlayout with options for preventing overlap, padding, and spacing.node: styles nodes with size, label placement, font size, and color palette grouped byentity_type.edge: styles edges dynamically based onweightproperty, capping line width at 10.
Destroys any existing graph instance before assigning and rendering the new one.
Tooltip Content Logic
Displays combo labels in red.
For nodes and edges, shows:
ID as header.
Optional entity type, weight, and description.
Styles tooltip colors based on element type (combo, node, edge).
Rendered Output
A
<div>container styled to take full width and height.Visibility toggled by the
showprop.The graph canvas is mounted inside this container by the G6 library.
Usage Example
import React, { useState } from 'react';
import ForceGraph from './force-graph';
const sampleData = {
nodes: [
{ id: 'node1', entity_type: 'Person', comboId: 'group1', description: 'A person node' },
{ id: 'node2', entity_type: 'Company', comboId: 'group1' },
],
edges: [
{ source: 'node1', target: 'node2', weight: 3 },
],
};
const App = () => {
const [showGraph, setShowGraph] = useState(true);
return (
<div style={{ width: '800px', height: '600px' }}>
<ForceGraph data={sampleData} show={showGraph} />
<button onClick={() => setShowGraph((prev) => !prev)}>
Toggle Graph
</button>
</div>
);
};
export default App;
Important Implementation Details
Combo Support: The component supports G6 combos (group nodes) for clustering related nodes visually. The
buildNodesAndCombosutility function (imported) is responsible for generating this hierarchical combo data from flat nodes.Performance Optimization: Uses React hooks
useMemoanduseCallbackto avoid unnecessary recalculations and re-renders.Dynamic Styling: Node colors are assigned based on the
entity_typefield using a palette grouping strategy; edge thickness reflects edge weight.Tooltip Plugin: Custom tooltip content adapts to the element hovered, providing contextual information with color-coded labels.
Lifecycle Management: Cleans up the previous graph instance before rendering a new one to prevent memory leaks.
Interaction with Other Files
./util-buildNodesAndCombos: This utility function processes raw node data into nodes and combos needed by the graph. It is critical for preparing the data structure for hierarchical visualization.@antv/g6: The primary graph visualization library used to render and manage the graph.lodash/isEmpty: Checks if the input data object is empty to avoid rendering on invalid data../index.less: Contains CSS styles applied to the graph container, controlling layout and appearance.
Visual Diagram
Below is a Mermaid component diagram illustrating the structure and interactions within the ForceGraph component:
componentDiagram
ForceGraph <|-- ReactComponent
ForceGraph : +props data:any, show:boolean
ForceGraph : +containerRef:Ref<HTMLDivElement>
ForceGraph : +graphRef:Ref<Graph|null>
ForceGraph : +nextData = useMemo()
ForceGraph : +render = useCallback()
ForceGraph : +useEffect to trigger render()
ForceGraph --> Graph : creates Graph instance (@antv/g6)
ForceGraph --> buildNodesAndCombos : prepares data (nodes & combos)
ForceGraph --> TooltipPlugin : custom tooltips for elements
ForceGraph --> styles : CSS styles for container
Summary
force-graph.tsx is a React component that encapsulates the creation and rendering of a force-directed graph visualization using G6. It:
Accepts graph data and visibility control.
Processes nodes and combos for hierarchical display.
Configures graph behaviors and styling for intuitive interaction.
Manages lifecycle of the graph instance efficiently.
Enhances user experience with informative tooltips and dynamic styles.
This makes it a reusable and powerful visualization component for applications requiring interactive exploration of relational data.
If you need further details about the buildNodesAndCombos utility or integration with the overall system, please provide related files or context.