Integrate the Hook


The previous lesson introduced a useDimensions hook that measures the width and height of a chart's parent container.

This lesson is a step by step tutorial on how to actually use it to make our chart responsive.

Members only
5 minutes read

1️⃣ Create a ref

Our goal is to measure the dimensions of a div that contains a chart and pass those dimensions to an SVG area.

The first step is to identify the target div. In React, this is possible thanks to a function called useRef. We already mentioned useRef in the axis module, with a video introducing how it works.

A ref can be initialized with the useRef function, like this:

const chartRef = useRef(null);

This ref called chartRef can now be passed to the container we want to measure.

return(
  <div ref={chartRef}>      // graph component container
    <MyChartComponent />    // graph that will have the same dimensions as the container
  </div>
)

This means that chartRef.current is now a way to select and manipulate the parent div with JavaScript!

2️⃣ Use the hook

If you remember, the useDimensions hook we built in the previous lesson expects a ref as input. That's exactly the ref we just created!

So we can pass our newly created chartRef to the hook, and it will return the dimensions to us.

Oh no! 😱

It seems like you haven't enrolled in the course yet!

Join many other students today and learn how to create bespoke, interactive graphs with d3.js and React!

Enrollment is currently closed. Join the waitlist to be notified when doors reopen:

Or Login