Open egorairo opened 9 months ago
@egorairo you need to check whether your ref is defined before using it. It seems like in this case it is not. Specifically when you're using SSR this is quite important as refs tend to be defined only on the client side.
@egorairo I ran into a similar problem using Next.js and trying to dynamically import this package.
Couple things that got it working for me:
'use client';
import { useEffect, useReducer, useRef, useState } from 'react'; import { forceY } from 'd3-force'; import ForceGraph2D from './ForceGraph2D';
export const Graph = props => { const { data } = props;
const graphRef = useRef(null);
const [hasInitialisedForces, setHasInitialisedForces] = useState(false);
const [tick, incrementTick] = useReducer(v => v + 1, 0);
useEffect(() => {
const graph = graphRef.current;
if (!graph || hasInitialisedForces) return;
graph.d3Force('center', null);
graph.d3Force('directional', forceY(100));
setHasInitialisedForces(true);
}, [tick, hasInitialisedForces]);
return (
<ForceGraph2D
ref={graphRef}
graphData={data}
onEngineTick={incrementTick}
/>
);
};
useEffect(() => {
if (fgRef.current) {
fgRef.current.d3Force(
'link',
forceLink()
.id((d: any) => {
return d.id;
})
.distance(24)
.strength(1),
);
}
}, []);```
You need to wrap it in a use affect so it only runs on the client. Had the issue because remix would try to run the code on the server and the useEffect helps
Hi! I'm trying to use d3force method but have error "d3Force is not a function". Could you please explain me why I am getting the error in the code below.