react-force-graph icon indicating copy to clipboard operation
react-force-graph copied to clipboard

How to increase the length of the link in 2D react-force-graph

Open Chinmay-k96 opened this issue 4 years ago • 9 comments

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

Chinmay-k96 avatar May 05 '21 11:05 Chinmay-k96

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 avatar May 05 '21 11:05 vasturiano

@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 avatar May 18 '22 11:05 chris-aeviator

@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

vasturiano avatar May 18 '22 14:05 vasturiano

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 avatar Jun 28 '22 15:06 andrea-lam

@andrea-lam as per the useRef docs, you probably want to do fgRef.current.d3Force.

vasturiano avatar Jun 28 '22 19:06 vasturiano

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!

andrea-lam avatar Jun 29 '22 07:06 andrea-lam

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.

vasturiano avatar Jun 29 '22 10:06 vasturiano

That solved the issue, thank you!

andrea-lam avatar Jun 29 '22 10:06 andrea-lam