Code Best Practices


All the charts in your codebase will need to be responsive. You'll likely apply the useDimensions hook from the previous lesson across all your chart components.

Let's explore a convention I use in my work to keep this clean and consistent.

Members only
5 minutes read

❌ The problem

When working with React, you want chart components that handle responsiveness on their own.

You don't want the parent component to be responsible for measuring the divs in which charts are rendered. Imagine a page with 10 charts: you would have to call the useDimensions hook 10 times in the parent, and that would quickly become a mess.

Instead, you want each chart component to offer a responsive version. Rather than calling a Barplot component in the parent, you call a ResponsiveBarplot component.

πŸ“¦ Wrapper component

This responsive version can be obtained by wrapping the chart component itself.

The wrapper creates a div around the non-responsive version, measures it, and passes the width and height along with all the other props:

// Responsive component = wrapper that manages the dimensions and does nothing else
export const ResponsiveBarplot = (props) => {
  const chartRef = useRef(null);

  const chartSize = useDimensions(chartRef);

  return (
    <div ref={chartRef} style={{ width: '100%', height: '100%' }}>
      <Barplot
        height={chartSize.height}
        width={chartSize.width}
        {...props} // pass all the props
      />
    </div>
  );
};

// Non responsive component
const Barplot = ({ width, height, data }) => {
  //... dataviz code goes here
}

Why It's Great:

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! πŸ™