The useDimensions Hook


Our SVG area needs a width and height, but we don't want to hardcode them if we want the chart to be responsive.

Let's learn how to measure the parent div that wraps the chart and listen for size changes.

Members only
5 minutes read

The problem

All the chart components we've built so far include an SVG element with fixed dimensions. For instance, a basic barplot component looks like this:

export const Barplot = () => {
  const width = 800;
  const height = 400;

  return (
    <svg width={width} height={height}>
      {/* bars, axes, etc. */}
    </svg>
  );
};

We've hardcoded the width and height so far, but in real life this doesn't work. If you set a width of 800px for someone reading on a 600px-wide tablet, the chart will be cropped.

In practice, the chart is always wrapped in a fluid div with a controlled size β†’ often taking the full width of its container.

Our first step is to listen to that div's dimensions and retrieve its width and height whenever they change. Basically, we need the 2 big numbers below.

360 Γ— 240

width Γ— height (px)

360px
240px

Drag the sliders to resize the device. Your chart component needs to know these exact pixel values to render correctly.

Oh no! 😱

This lesson isn’t available just yet.

Take a look at the status badges next to each lesson in the sidebar to see when it’s coming out.

Thanks for your patience! πŸ™