Drawing our peripherals in React
We take a naive approach to creating an Axis component
Drawing our peripherals#
Next, we want to draw our axes. This is where even experienced d3.js and React.js developers get confused because both libraries want to handle creating new the DOM elements. Up until now, we've used
d3.axisLeft() to append multiple
<text> elements to a manually created
<g>. element. But the core concept of React.js relies on giving it full control over the DOM.
Let's first make a naive attempt at an Axis component, mimicking the d3.js code we've written so far. Since our Axis component is already imported, we can create a new instance in our render method. We'll need to specify the
dimension and relevant
scale of both of our axes.
Remember that SVG elements' z-indices are determined by their order in the DOM. If you want your line to overlap your axes, make sure to add the
<Axis>components before the
<Line>in your render method.
Let's head over to
src/Chart/Axis-naive.jsx to flesh out our Axis component. There's not much going on here yet, just a basic React Component that accepts a dimension (either x or y), a scale, and a tick formatting function.
Let's start by pulling in the dimensions of our chart, using the custom React hook we created earlier.
Since we'll want to use
d3.axisLeft(), based on the
dimension prop, let's make a map so we can dynamically grab the correct d3 method. This is one of many abstractions that can help to keep our chart library's API simple for collaborators less familiar with d3.