react-d3-graph

2.4.1

Quick Links

πŸ”— GitHub Repo

πŸ”— Live Demo

Versions

graph.config

This is certainly the only extra piece of documentation that you will ever need


Here you can consult a detailed description of each graph configurable property as well as the default values of those properties.

Note about performance
Some of the properties have a major performance impact when toggled while rendering graphs of medium or large dimensions (hundreds or thousand of elements). These properties are marked with πŸš…πŸš…πŸš….
⭐ tip to achieve smoother interactions you may want to provide a toggle to set staticGraph or (better) staticGraphWithDragAndDrop to true

Note about granularity
Some of the properties listed in the Node section are marked with πŸ”πŸ”πŸ”. This means that this properties have a higher level of granularity. These properties can be defined in the graph payload at a node level. (sample payload below)

const graph = {
    nodes: [
        {
            id: "id",
            color: "red",         // only this node will be red
            size: 300,            // only this node will have size 300
            symbolType: "diamond" // only this node will have "diamond" shape
        }
    ],
    links: [...]
};


# Graph global configurations

graph.config
Parameters
automaticRearrangeAfterDropNode (boolean = false) πŸ”— πŸš…πŸš…πŸš… when true performing a node drag and drop should automatically rearrange all nodes positions based on new position of dragged node (note: staticGraph should be false). A few notes on this property:
  • automaticRearrangeAfterDropNode needs to be set before the first graph render. Only the first set value will take effect.
  • automaticRearrangeAfterDropNode won't work together with nodeHighlightBehavior (currently a known limitation, to be address in the future GitHub issue #261).
collapsible (boolean = false) πŸ”— πŸš…πŸš…πŸš… Allow leaf neighbors nodes to be collapsed (folded), this will allow users to clear the way out and focus on the parts of the graph that really matter. To see an example of this behavior you can access this sandbox link that has a specific set up to experiment this feature. NOTE : At this moment nodes without connections (orphan nodes) are not rendered when this property is activated (see GitHub issue #129 ).
directed (boolean = false) πŸ”— This property makes react-d3-graph handle your graph as a directed graph. It will out of the box provide the look and feel of a directed graph and add directional semantic to links. You can see a sample in the image below.
focusZoom (number = 1) πŸ”— zoom that will be applied when the graph view is focused in a node. Its value must be between minZoom and maxZoom . If the specified focusZoom is out of this range, minZoom or maxZoom will be applied instead.
NOTE : This animation is not trigger by default. In order to trigger it you need to pass down to react-d3-graph the node that you want to focus via prop focusedNodeId along side with nodes and links:
const data = {
   nodes: this.state.data.nodes,
   links: this.state.data.links,
   focusedNodeId: "nodeIdToTriggerZoomAnimation"
};
focusAnimationDuration (number = 0.75) πŸ”— duration (in seconds) for the animation that takes place when focusing the graph on a node.
height (number = 400) πŸ”— the height of the (svg) area where the graph will be rendered.
nodeHighlightBehavior (boolean = false) πŸ”— πŸš…πŸš…πŸš… when user mouse hovers a node that node and adjacent common connections will be highlighted (depending on the highlightDegree value). All the remaining nodes and links assume opacity value equal to highlightOpacity .
linkHighlightBehavior (boolean = false) πŸ”— πŸš…πŸš…πŸš… when the user mouse hovers some link that link and the correspondent nodes will be highlighted, this is a similar behavior to nodeHighlightBehavior but for links (just for historical reference this property was introduced in v1.0.0 ) .
highlightDegree (number = 1) πŸ”— Possible values: 0, 1 or 2 . This value represents the range of the highlight behavior when some node is highlighted. If the value is set to 0 only the selected node will be highlighted. If the value is set to 1 the selected node and his 1st degree connections will be highlighted. If the value is set to 2 the selected node will be highlighted as well as the 1st and 2nd common degree connections.
highlightOpacity (number = 1) πŸ”— this value is used to highlight nodes in the network. The lower the value the more the less highlighted nodes will be visible (related to nodeHighlightBehavior ).
maxZoom (number = 8) πŸ”— max zoom that can be performed against the graph.
minZoom (number = 0.1) πŸ”— min zoom that can be performed against the graph.
panAndZoom (boolean = false) πŸ”— πŸš…πŸš…πŸš… pan and zoom effect when performing zoom in the graph, a similar functionality may be consulted here .
staticGraph (boolean = false) πŸ”— when setting this value to true the graph will be completely static, thus all forces and drag events upon nodes will produce not effect. Note that, if this value is true the nodes will be rendered with the initial provided x and y coordinates (links positions will be automatically set from the given nodes positions by rd3g), no coordinates will be calculated by rd3g or subjacent d3 modules.
staticGraphWithDragAndDrop (boolean?) πŸ”— exactly the same as above staticGraph , but it will allow users to drag&drop nodes. Note : If staticGraph is set to true , then staticGraphWithDragAndDrop will not produce the desired behaviour, make sure to set only one of them to true .
width (number = 800) πŸ”— the width of the (svg) area where the graph will be rendered.
d3 (Object) d3 object is explained in next section. ⬇️

# d3 level configurations

Name Description
d3.alphaTarget number (default 0.05) πŸ”— see d3-force simulation.alphaTarget
d3.gravity number (default -100) πŸ”— this will define how close nodes are to each other see d3 reference for forces .
  • If value is positive, nodes will attract each other.
  • If value is negative, nodes will repel each other. Most of the times this is what we want, so nodes don"t overlap.
d3.linkLength number (default 100) πŸ”— the length of each link from the center of the nodes it joins.
d3.linkStrength number (default 1) πŸ”— see d3-force link.strength
d3.disableLinkForce number (default false) πŸ”— ⚠️πŸ§ͺEXPERIMENTALπŸ§ͺ⚠️ it completely disables d3 force link and simulation to re-trigger so that one can obtain precise render of node positions as described by the author @antoninklopp in the Pull Request description .
node (Object) node object is explained in next section. ⬇️

# Node level configurations

Name Description
node.color string (default "#d3d3d3") πŸ”— πŸ”πŸ”πŸ” this is the color that will be applied to the node if no color property
is found inside the node itself (yes you can pass a property "color" inside
the node and that color will override the this default one ).
node.fontColor string (default "black") πŸ”— πŸ”πŸ”πŸ” fill color for node"s svg label.
node.fontSize number (default 8) πŸ”— font-size property for all nodes" labels.
node.fontWeight string (default "normal") πŸ”— font-weight property for all nodes" labels.
node.highlightColor string (default "SAME") πŸ”— color for all highlighted nodes (use string "SAME" if you want the node to keep its color in highlighted state).
node.highlightFontSize number (default 8) πŸ”— fontSize in highlighted state.
node.highlightFontWeight string (default "normal") πŸ”— fontWeight in highlighted state.
node.highlightStrokeColor string (default "SAME") πŸ”— strokeColor in highlighted state.
node.highlightStrokeWidth number (default "SAME") πŸ”— strokeWidth in highlighted state.
node.labelProperty (string | Function) (default "id") πŸ”— this is the node property that will be used in runtime to
fetch the label content. You just need to add some property (e.g. firstName) to the node payload and then set
node.labelProperty to be "firstName" . This can also be a function! , if you pass a function here it will be called
to obtain the label value on the fly, as a client you will receive all the node information that you passed down into react-d3-graph,
so the signature of the function would be:
function myCustomLabelBuilder(node) {
    // do stuff to get the final result...
    return "label string";
}

Then you just need to make sure that you pass this function in the config in config.node.labelProperty.

node.mouseCursor string (default "pointer") πŸ”— cursor property for when some node is mouse hovered.
node.opacity number (default 1) πŸ”— πŸ”πŸ”πŸ” by default all nodes will have this opacity value.
node.renderLabel boolean (default true) πŸ”— πŸ”πŸ”πŸ” when set to false no labels will appear along side nodes in the graph.
node.size number (default 200) πŸ”— πŸ”πŸ”πŸ” defines the size of all nodes.
node.strokeColor string (default "none") πŸ”— πŸ”πŸ”πŸ” this is the stroke color that will be applied to the node if no strokeColor property is found inside the node itself (yes you can pass a property "strokeColor" inside the node and that stroke color will override this default one ).
node.strokeWidth number (default 1.5) πŸ”— πŸ”πŸ”πŸ” the width of the all node strokes.
node.svg string (default "") πŸ”— πŸ”πŸ”πŸ” render custom svg for nodes in alternative to node.symbolType . This svg can be provided as a string to either a remote svg resource or for a local one.
node.symbolType string (default "circle") πŸ”— πŸ”πŸ”πŸ” the shape of the node. Use the following values under a property type inside each node (nodes may have different types, same as colors):
  • "circle"
  • "cross"
  • "diamond"
  • "square"
  • "star"
  • "triangle"
  • "wye"

[note] react-d3-graph will map this values to d3 symbols

node.viewGenerator Function (default null) πŸ”— πŸ”πŸ”πŸ” function that receives a node and returns a JSX view.
link (Object) link object is explained in the next section. ⬇️
Name Description
link.color string (default "#d3d3d3") πŸ”— πŸ”πŸ”πŸ” the color for links (from version 1.3.0 this property can be configured at link level).
link.fontColor string (default "black") πŸ”— πŸ”πŸ”πŸ” fill color for link's svg label.
link.fontSize number (default 8) πŸ”— font-size property for all links' labels.
link.fontWeight string (default "normal") πŸ”— font-weight property for all links' labels.
link.highlightColor string (default "SAME") πŸ”— links' color in highlight state, default being the same color as link.color .
link.highlightFontSize number (default 8) πŸ”— font-size in highlighted state.
link.highlightFontWeight string (default "normal") πŸ”— font-weight in highlighted state.
link.labelProperty (string | Function) (default "label") πŸ”— the property that will be rendered as label within some link. Note that
this property needs to be passed along the link payload (along side with source and target). This property can also be a function
that receives the link itself as argument and returns a custom string, similarly to what happens with node.labelProperty .
link.mouseCursor string (default "pointer") πŸ”— cursor property for when link is mouse hovered.
link.opacity number (default 1) πŸ”πŸ”πŸ” - πŸ”— the default opacity value for links.
link.renderLabel boolean (default false) πŸ”— when set to true labels will appear along side links in the graph. Note : this will only happen of course if proper label is passed within the link, check also link.labelProperty .
link.semanticStrokeWidth boolean (default false) πŸ”— when set to true all links will have "semantic width" , this means that the width of the connections will be proportional to the value of each link. This is how link strokeWidth will be calculated:
strokeWidth += (linkValue * strokeWidth) / 10;
link.strokeWidth number (default 1.5) πŸ”— πŸ”πŸ”πŸ” strokeWidth for all links. By default the actual value is obtain by the following expression:
link.strokeWidth * (1 / transform); // transform is a zoom delta Ξ” value
link.markerHeight number (default 6) πŸ”— markerHeight property for the link arrowhead height. Note: this property can only be set in the first mount, it does not update dynamically.
link.markerWidth number (default 6) πŸ”— markerWidth property for the link arrowhead width. Note: this property can only be set in the first mount, it does not update dynamically.
link.type string (default "STRAIGHT") πŸ”— πŸ”πŸ”πŸ” the type of line to draw, available types at this point are:
  • "STRAIGHT" (default) - a straight line.
  • "CURVE_SMOOTH" - a slight curve between two nodes
  • "CURVE_FULL" - a semicircumference trajectory unites source and target nodes.
Example
// A simple config that uses some properties
const myConfig = {
    nodeHighlightBehavior: true,
    node: {
        color: "lightgreen",
        size: 120,
        highlightStrokeColor: "blue"
    },
    link: {
        highlightColor: "lightblue"
    }
};

// Sorry for the long config description, here"s a potato πŸ₯”.

Graph

Graph component is the main component for react-d3-graph components, its interface allows its user to build the graph once the user provides the data, configuration (optional) and callback interactions (also optional). The code for the live example can be consulted here

new Graph(props: any)

Extends React.Component

Parameters
props (any)
Example
import { Graph } from 'react-d3-graph';

// graph payload (with minimalist structure)
const data = {
    nodes: [
      {id: 'Harry'},
      {id: 'Sally'},
      {id: 'Alice'}
    ],
    links: [
        {source: 'Harry', target: 'Sally'},
        {source: 'Harry', target: 'Alice'},
    ]
};

// the graph configuration, you only need to pass down properties
// that you want to override, otherwise default ones will be used
const myConfig = {
    nodeHighlightBehavior: true,
    node: {
        color: 'lightgreen',
        size: 120,
        highlightStrokeColor: 'blue'
    },
    link: {
        highlightColor: 'lightblue'
    }
};

// Callback to handle click on the graph.
// @param {Object} event click dom event
const onClickGraph = function(event) {
     window.alert('Clicked the graph background');
};

const onClickNode = function(nodeId) {
     window.alert('Clicked node ${nodeId}');
};

const onDoubleClickNode = function(nodeId) {
     window.alert('Double clicked node ${nodeId}');
};

const onRightClickNode = function(event, nodeId) {
     window.alert('Right clicked node ${nodeId}');
};

const onMouseOverNode = function(nodeId) {
     window.alert(`Mouse over node ${nodeId}`);
};

const onMouseOutNode = function(nodeId) {
     window.alert(`Mouse out node ${nodeId}`);
};

const onClickLink = function(source, target) {
     window.alert(`Clicked link between ${source} and ${target}`);
};

const onRightClickLink = function(event, source, target) {
     window.alert('Right clicked link between ${source} and ${target}');
};

const onMouseOverLink = function(source, target) {
     window.alert(`Mouse over in link between ${source} and ${target}`);
};

const onMouseOutLink = function(source, target) {
     window.alert(`Mouse out link between ${source} and ${target}`);
};

const onNodePositionChange = function(nodeId, x, y) {
     window.alert(`Node ${nodeId} moved to new position x= ${x} y= ${y}`);
};


<Graph
     id='graph-id' // id is mandatory, if no id is defined rd3g will throw an error
     data={data}
     config={myConfig}
     onClickGraph={onClickGraph}
     onClickNode={onClickNode}
     onDoubleClickNode={onDoubleClickNode}
     onRightClickNode={onRightClickNode}
     onClickLink={onClickLink}
     onRightClickLink={onRightClickLink}
     onMouseOverNode={onMouseOverNode}
     onMouseOutNode={onMouseOutNode}
     onMouseOverLink={onMouseOverLink}
     onMouseOutLink={onMouseOutLink}/>
Instance Members
β–Έ _generateFocusAnimationProps
β–Έ _graphLinkForceConfig()
β–Έ _graphNodeDragConfig()
β–Έ _graphBindD3ToReactComponent()
β–Έ _onDragEnd
β–Έ _onDragMove
β–Έ _onDragStart
β–Έ _setNodeHighlightedValue
β–Έ _tick
β–Έ _zoomConfig
β–Έ _zoomed
β–Έ onClickGraph
β–Έ onClickNode
β–Έ onMouseOverNode
β–Έ onMouseOutNode
β–Έ onNodePositionChange
β–Έ pauseSimulation
β–Έ resetNodesPositions
β–Έ restartSimulation
β–Έ UNSAFE_componentWillReceiveProps(nextProps)

Graph/renderer

Offers a series of methods that isolate render logic for Graph component.

Graph/renderer
Static Members
β–Έ _renderNodes(nodes, nodeCallbacks, config, highlightedNode, highlightedLink, transform, linksMatrix)
β–Έ _renderDefs()
β–Έ _memoizedRenderDefs
β–Έ renderGraph(nodes, nodeCallbacks, links, linksMatrix, linkCallbacks, config, highlightedNode, highlightedLink, transform)

Graph/builder

Offers a series of methods that isolate the way graph elements are built (nodes and links mainly).

Graph/builder
Static Members
β–Έ _getNodeOpacity(node, highlightedNode, highlightedLink, config)
β–Έ buildLinkProps(link, nodes, links, config, linkCallbacks, highlightedNode, highlightedLink, transform)
β–Έ buildNodeProps(node, config, nodeCallbacks, highlightedNode, highlightedLink, transform)

Graph/helper

Offers a series of methods that isolate logic of Graph component and also from Graph rendering methods.

Graph/helper
Static Members
β–Έ Node
β–Έ _createForceSimulation(width, height, gravity)
β–Έ _initializeNodes(graphNodes)
β–Έ _tagOrphanNodes(nodes, linksMatrix)
β–Έ _validateGraphData(data)
β–Έ _pickId(o)
β–Έ _pickSourceAndTarget(o)
β–Έ checkForGraphElementsChanges(nextProps, currentState)
β–Έ checkForGraphConfigChanges(nextProps, currentState)
β–Έ getCenterAndZoomTransformation(d3Node, config)
β–Έ getId(sot)
β–Έ initializeGraphState(props, state)
β–Έ updateNodeHighlightedValue(nodes, links, config, id, value)

Graph/collapse-helper

Offers a series of methods that allow graph to perform the necessary operations to create the collapsible behavior. These functions will most likely operate on the links matrix.

Graph/collapse-helper
Static Members
β–Έ _isLeafDirected(inDegree, outDegree)
β–Έ _isLeafNotDirected(inDegree, outDegree)
β–Έ _isLeaf(nodeId, linksMatrix, directed)
β–Έ computeNodeDegree(nodeId, linksMatrix)
β–Έ getTargetLeafConnections(rootNodeId, linksMatrix, config)
β–Έ isNodeVisible(nodeId, nodes, linksMatrix)
β–Έ toggleLinksConnections(d3Links, connectionMatrix)
β–Έ toggleLinksMatrixConnections(linksMatrix, connections, config)

Node

Node component is responsible for encapsulating node render.

new Node()

Extends React.Component

Example
const onClickNode = function(nodeId) {
    window.alert('Clicked node', nodeId);
};

const onRightClickNode = function(nodeId) {
    window.alert('Right clicked node', nodeId);
}

const onMouseOverNode = function(nodeId) {
    window.alert('Mouse over node', nodeId);
};

const onMouseOutNode = function(nodeId) {
    window.alert('Mouse out node', nodeId);
};

const generateCustomNode(node) {
    return <CustomComponent node={node} />;
}

<Node
    id='nodeId'
    cx=22
    cy=22
    fill='green'
    fontSize=10
    fontColor='black'
    fontWeight='normal'
    dx=90
    label='label text'
    opacity=1
    renderLabel=true
    size=200
    stroke='none'
    strokeWidth=1.5
    svg='assets/my-svg.svg'
    type='square'
    viewGenerator={generateCustomNode}
    className='node'
    onClickNode={onClickNode}
    onRightClickNode={onRightClickNode}
    onMouseOverNode={onMouseOverNode}
    onMouseOutNode={onMouseOutNode} />
Instance Members
β–Έ handleOnClickNode
β–Έ handleOnRightClickNode
β–Έ handleOnMouseOverNode
β–Έ handleOnMouseOutNode

Node/helper

Some methods that help no the process of rendering a node.

Node/helper
Static Members
β–Έ _convertTypeToD3Symbol(typeName)
β–Έ buildSvgSymbol(size, symbolTypeDesc)

Link component is responsible for encapsulating link render.

new Link()

Extends React.Component

Example
const onClickLink = function(source, target) {
     window.alert(`Clicked link between ${source} and ${target}`);
};

const onRightClickLink = function(source, target) {
     window.alert(`Right clicked link between ${source} and ${target}`);
};

const onMouseOverLink = function(source, target) {
     window.alert(`Mouse over in link between ${source} and ${target}`);
};

const onMouseOutLink = function(source, target) {
     window.alert(`Mouse out link between ${source} and ${target}`);
};

<Link
    d="M1..."
    source="idSourceNode"
    target="idTargetNode"
    markerId="marker-small"
    strokeWidth=1.5
    stroke="green"
    className="link"
    opacity=1
    mouseCursor="pointer"
    onClickLink={onClickLink}
    onRightClickLink={onRightClickLink}
    onMouseOverLink={onMouseOverLink}
    onMouseOutLink={onMouseOutLink} />
Instance Members

Link/helper

A set of helper methods to manipulate/create links.

Link/helper
Static Members
β–Έ straightLineRadius()
β–Έ smoothCurveRadius(x1, y1, x2, y2)
β–Έ fullCurveRadius()
β–Έ getRadiusStrategy(type)
β–Έ buildLinkPathDefinition(link, type)

Link/const

A set of constants that facilitate readability regarding links.

Link/const
Static Members
β–Έ LINE_TYPES

Marker

Market component provides configurable interface to marker definition.

new Marker()

Extends React.Component

Example
<Marker id="marker-id" fill="black" />

Marker/helper

Offers a series of methods to compute proper markers within a given context.

Marker/helper
Static Members
β–Έ _markerKeyBuilder(size, highlighted)
β–Έ _getMarkerSize(transform, mMax, lMax)
β–Έ _computeMarkerId(highlight, transform, config)
β–Έ _memoizedComputeMarkerId()
β–Έ getMarkerId

utils

Offers a series of generic methods for object manipulation, and other operations that are common across rd3g such as error logging.

utils
Static Members
β–Έ _isPropertyNestedObject(o, k)
β–Έ isDeepEqual(o1, o2, _depth)
β–Έ isEmptyObject(o)
β–Έ deepClone(o, _clone, _depth)
β–Έ merge(o1, o2, _depth)
β–Έ pick(o, props)
β–Έ antiPick(o, props)
β–Έ buildFormattedErrorMessage(component, msg)
β–Έ throwErr(component, msg)
β–Έ logError(component, msg)
β–Έ logWarning(component, msg)