How to translate a D3js project into react style code

Hi, i hope this is the correct place to ask this question.
As the title says, how to translate a project on d3js.org into a react style code.

A little background. I am an experienced programmer with more traditional languages and my workplace now requires that i get experienced in JavaScript. And i have been following Curran Kelleher’s 11 hour long tutorial on FreeCodeCamp’s youtube channel.
It’s a very good tutorial.

But, and here is where the question arises from.
The coding style and logic is completely different from the examples on d3js.
(i don’t know if there is a name for these styles to more easily identify them)

I have been playing with the Force-direct example (https://observablehq.com/@d3/force-directed-graph)
I can get it up and running by copying the code, but i am completely stumped as to how am i going to translate this into the React-style of coding

I want it in the react-style because it is more familiar to me because of my background and i feel i have better control over the code that way.

Does anyone know of any resources i can look at to help me with this?
youtube articles or tutorials or similar things. I don’t even know what to search for because i don’t know the name of the different coding styles.

Thank you

here is a link I found useful
https://wattenberger.com/blog/react-and-d3
basically you use the useRef and useEffect hooks to mimic vanilla d3. I hope this helps.

1 Like

Thank you
This looks helpful
I will try it out

@Roger This is a great question!

Yes, I realize there is a huge disconnect.

I would agree that once you have a solid grasp of useRef and useEffect, you can use it to compartmentalize your codebase into “React style” and “D3 style”. Inside the useEffect hook you can invoke some function that implements rendering and other side effects using D3.

In the case of a force layout, this can work, but be careful to stop the simulation when tearing down the component.

All of that might look something like this:

const ForceDirectedGraph = ({data}) => {
  const ref = useRef();
  useEffect(() => {
    const stopSimulation = d3BasedForceLayout(ref.current, data);

    // The function you return from `useEffect` runs when the component is torn down.
    // You can use it to stop/cancel long running side effects such as d3.timer or the ticks of a force simulation.
    // If you don't do this, you might have a zombie timer that breaks things.
    return stopSimulation;
  }, [data])
  return <g ref={ref} />