This video is available to students only

Drawing our canvas in React

We create our wrapper and bounds within our Chart component to prevent from having to repeat ourselves for every chart we create.

Drawing our canvas#

Next up, we need to create our canvas. Since we'll want a canvas for all of our charts, we can put most of this logic in the Chart component. Let's add a Chart to our render method and pass it our dimensions.

When we look at our dashboard again, not much has changed. Let's open up src/Chart/Chart.jsx to see what we're starting with.

Chart is a very basic functional React component — it asks for only one prop: dimensions.

We're defining useDimensionsContext() at the top of our file as an empty function to prevent import errors in another file. We'll update it in a minute.

The children in a Chart can be any component from our chart library (or raw SVG elements). Each of these components might need to know the dimensions of our chart — for example, an Axis component might need to know how tall to be. Instead of passing dimensions to each of these components as a prop, we can create a React Context that defines the dimensions for the whole chart.

 

This page is a preview of Fullstack D3 Masterclass

Please select a discussion on the left.