react-force-graph
react-force-graph copied to clipboard
How to increase the length of the link in 2D react-force-graph
what prop can i use to control the length of the link in a 2D react-force-graph. i have seen something like d3Force('link).distance() in another issue but i am not able to use this as a prop in a react component ForceGraph2D. how can use it in a react component
As mentioned in the docs, d3Force is a component method, not prop. It should be invoked via forward ref.
You can see an example of its use here:
https://github.com/vasturiano/react-force-graph/blob/e67177b3522e2ffd212f807cbb6b74ed04a39ab6/example/collision-detection/index.html#L34
@vasturiano your reply answers the question how to add collide but not distance. Why is the method repeated and how does the correct usage of distance look like?
@chris-aeviator to modify the distance setting (per link) of the existing link force you can just do something like:
fg.d3Force('link').distance(link => /* your code */);
Docs about this method from the d3-force module: https://github.com/d3/d3-force#link_distance
Hi @vasturiano ,
I am currently trying to do something similar, but am struggling to access d3Force. Below is the relevant code in the javascript file for the graph.
import {ForceGraph2D, ForceGraph3D} from "react-force-graph";
import React, {useRef, useState, useCallback, useEffect} from "react";
const ForceGraph = (props) => {
let graphData = props.data
const fg = useRef();
fg.d3Force('link').distance(link => /* my code */);
}
return (
<ForceGraph2D
className="forceGraph"
ref={fgRef}
graphData={graphData}
/>
)
I get the error: "Uncaught TypeError: fg.d3Force is not a function".
@andrea-lam as per the useRef docs, you probably want to do fgRef.current.d3Force.
Hi @vasturiano, Thank you for your reply, I tried your suggestion and it resulted in the same error. It seems like a similar problem to this issue: https://github.com/vasturiano/react-force-graph/issues/187, but a javascript solution wasn't given there. Thank you!
I recommend you place this instruction in a useEffect call that runs once at post-mount. I suspect the issue here is that on component mount your ref has yet not been populated, that only happens when the JSX is interpreted on your return statement. Therefore it will be null on your first run.
That solved the issue, thank you!