Drawing our canvas

<CodeSandboxEmbed src="//codesandbox.io/s/9cs4i?fontsize=14&hidenavigation=1&theme=dark&autoresize=1&module=/src/Timeline.jsx" style={{width: '100%', height: '35em'}} />

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.

First, we'll use the native React createContext() to create a new context — this code will go outside of the component, after our imports.

 

This page is a preview of Fullstack D3 Masterclass

Start a new discussion. All notification go to the author.