A simple dashboard using React hooks and D3 — Part II

The bar Chart component is just a series of <rect> svg elements which properties and animations will be handled by D3, data will be provided by the App React state and data changes will be triggered by React hooks. As said in part I this component is stateless, passing the filtering selectedGroup and the fill props of the slice will be enough for D3 to resize bars heights and change their colours with a transition.

Same as we did for the Donut component we split the bar chart into two functional components. Let’s have a look at the code.

BarChart Component

The BarChart component keeps together all chart bars and static labels. y is the function that calculates the height of each bar, scaling it according to the values domain of our data. Domain is given to define the data extent (from min to max value) and range is used to scale these values from 0 to the maximum height that we want the bars to have in our chart, in this case 50px (100 - 20 - 30).

Bar Component

Bar wraps in a React component our svg <rect> element and the dynamic text displaying the count for each category on the top part as a <text> label.

From this example we can see that we can have useEffect in a stateless component too, triggering side effects each time it will render. Since we have no state, the hook is invoked whenever any of the props changes. In this case declaring which props will trigger the hook is redundant, all props of the Bar component will change at every render, for this reason we declare no array as second argument in useEffect.

In the same way we did for the donut component we create the key function that animates the bars on slice selection animateRect, again declared as variable outside any component.

const animateRect = (rectRef, height, colour, countTextRef) => {const rect = select(rectRef.current);
.attr("height", (height + 0.5) )
.attr("fill", colour);
const text = select(countTextRef.current);
.attr("y", ((4 + height) * -1));

Here is where D3 manipulates the DOM, changing the bars height property and colour fill using a transition.

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