A simple dashboard using React hooks and D3 — Part III

The Line Chart component is basically a line connecting a series of dots placed on the coordinate system of our svg canvas. In this example, on the x axis we have the years referred to the sales of items and on the y axis we have the amount of sales for that year. On top of the line we will plot the dots in correspondence with their x,y position, the dots fill colour will be white except for the minimum and maximum y value, these will be red and green respectively. Let’s have a look at the code.

Translated in React and svg, the component will combine the and the components. The first one is a element which x,y coordinates are adequately scaled to our data with d3, the second component encapsulates an array of elements placed on top of these coordinates, hence they will be scaled in the same way as our line. The react components have their own hook that will fire up a method to animate the svg element inside them, using the d3 DOM manipulations methods and transitions. Our component will have its own data source in a separate file, the props passed from the parent will update the props on the children component that will in turn trigger the hook and the animations, the same way we designed it for Our Donut and Slice components.

While the process of animation of the component is not much different than the component (d3 updating the attribute of the our svg element) when we will animate the we will have to follow a slightly different process. The function expects both the group svg element, containing all our together, and the containing the array of data which is updated on each slice selection.

Since we expect the number of dots to be the same as the number of data items, we first iterate/map our data in the variable; calculating the updated x,y coordinates for each data item using the and functions. Secondly, using the d3 function we select all in our group and we iterate through them, again using the function of d3. We will apply the new coordinates in to the and properties of matching the index of each element in both arrays, has as second argument the index of each item in the selected group.

The Line chart component contains more text and colour definitions for its children components, as the process of creating and updating these is the same as we used for both the Bar and Donut component you can have a look at how these is made to get an idea of how the animations work.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store