liveBook · Manning

Ref

As explained in D3.js in Action, Third Edition

A React ref is an object or callback mechanism that provides access to a rendered component or DOM element.

A React ref gives code access to a rendered element so another tool, such as D3, can control that element directly. With useRef(), attach the ref to an element, then read its current property after rendering. section 8.5.1

Use a ref to connect React-rendered markup with D3:

  • Import useRef and useEffect from React, then initialize a ref such as scatterplotRef = useRef(). section 8.5.1
  • Attach the ref to the element D3 should control, for example <g ref={scatterplotRef}></g>. section 8.5.1
  • Inside useEffect, select the current rendered element with d3.select(scatterplotRef.current). section 8.5.1
  • Keep D3 operations inside the effect so they work with the up-to-date rendered element. section 8.5.1

Animating a curve path

A hybrid chart can let React render a path while a ref lets D3 animate its d attribute. The effect selects pathRef.current, applies a transition, and reruns when the data or line generator changes. section 8.7

Figure 8.5 To let D3 control a portion of the DOM in React, we first need to import the useRef() and the useEffect() hooks into our component. We then initialize a ref and attach it as an attribute to the element we want to control with D3. Finally, inside a useEffect() hook, we select the current instance of the ref and start using D3 as usual.
figure

The diagram shows the complete handoff: initialize useRef, attach the ref, select its current element inside useEffect, and continue with D3. section 8.5.1

How D3.js in Action, Third Edition covers it

How deep it goes
Explains initialization, attachment, current-element selection, and effect placement through chart implementations.
Examples
Uses a D3-controlled scatterplot and a hybrid rankings visualization with animated curve paths.
What you can do after
Apply it via useRef, useEffect, and D3 to select and animate rendered chart elements.
How it connects
Links React hooks, useEffect, D3 selections, DOM elements, SVG paths, and transitions.

Also explained in

Compare how 3 books explain ref →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.