Make a clever Bitcoin price chart with React and D3.
To get started real quick on this project, I bootstrapped the application with create-react-app, a comfortable environment for learning React, and probably best way to start building a new single-page application in React. Under the hood, it uses Babel and webpack, but you don’t need to know anything about them.
I’ll start with code in my root component, App.js which is responsible for fetching data from the free coindesk API, formatting the raw data and passing it to the child component as a prop.
Okay, I understand this is somewhat a lot of code but I’ll try to break it down. What you should focus on is the fetch browser API inside the componentDidMount lifecycle method. When the component is mounted and before the render method is called, A fetch request is made to the coindesk API which returns a promise that is handled appropriately using JavaScript promises.
The bitcoin price index(bpi) data returned is in this format "2019-12-05":7404.4033 in an array hence the need to format the dates to actual date objects instead of strings before adding it to state. These actual date objects will be helpful while creating the scale for the horizontal axis on the actual graph. This data is then passed to the child component as props.
Okay I know this is really a lot of code because it’s where the heavy lifting takes place. You shouldn’t be worried though, I got you on this! Let’s start breaking it down.
None of the following steps is very difficult, it’s just chaining them all together that was a little tricky, at first.
Before anything else, you need to first install D3 from npm or yarn.
For npm users, use the command npm install d3 and for yarn users, use the command yarn add d3
Step 1 — Receiving the data
const = nextProps;if (!data) return ;
Our focus in file should be on the getDerivedStateFromProps method in the Chart component. It receives props from the root component and pulls of the data prop. If the data is not available, it will do nothing.
Step 2 — Calculating the horizontal and vertical scales
const xExtent = d3.extent(data, d => d.date);const yExtent = d3.extent(data, d => d.price);const xScale = d3
.scaleTime()
.domain(xExtent)
.range([margin.left, width - margin.right]);const yScale = d3
.scaleLinear()
.domain(yExtent)
.range([height - margin.bottom, margin.top]);
If the data is available, the both the horizontal and vertical scales are calculated by leveraging D3’s scaleTime() scaleLinear() methods. The results are stored in the xScale and yScale variables respectively. In both cases, the margin is considered while specifying the array values for the range.
Step 3 — Calculating the line and area
const line = d3
.line()
.x(d => xScale(d.date))
.y(d => yScale(d.price));const minY = d3.min(data, d => d.price);const area = d3
.area()
.x(d => xScale(d.date))
.y0(d => yScale(minY))
.y1(d => yScale(d.price));return ;
The line and area of the chart are also calculated by leveraging D3’s line() and area() methods and the results stored in the line and area variables respectively. The getDerivedStateFromProps method will then return the xScale, yScale, line and area variables together with the data prop which can then be accessed in the render method from state.
Step 4 — Rendering the line and area to the svg.
<path
id=
d=
stroke="#6788ad"
fill="transparent"
/><path
id=
d=
fill="#6788ad"
style=}
/>
Inside the render method, we return an svg element with both width and height properties. We then append two path elements for the line and area while passing them the data from state. At this point, we should be able to see the line and area chart in the react application.
Step 5 — Adding the axes
xAxis = d3.axisBottom();
yAxis = d3.axisLeft();
Just above the method getDerivedStateFromProps, we created two axes. The x-axis and the y-axis by leveraging D3’s axisBottom() and axisLeft() methods.
<g
ref="xAxis"
transform=)`}
/><g ref="yAxis" transform=, 0)`} />
Inside the svg element in the render method, we add two group elements each with a ref to either the xAxis or yAxis.
componentDidUpdate()
These refs are used in the componentDidUpdate method to call the axes on the group elements but before doing that, we need to first add the scales to the axes.
Okay, I’m on the home stretch now 🙂
Step 6 — Labeling the axes
<text
transform=, $)`}
>
Dates for the last 30 days
</text><text
transform=) rotate(270)`}
>
Amount in USD
</text>
The final step involves adding labels to our graph’s axes. Imagine a graph without labelled axes, Huh?! This means some information would still be missing about the graph. So we add two text elements to the svg element in the render method. One text element will add a label for the x-axis and another for the y-axis.
And you’ve successfully visualized bitcoin’s 30 day price chart with React and D3. Not too tough.
Conclusion
At first glance, visualizing bitcoin data with React and D3 seems a bit daunting. Actually D3 helps make a major factor (creating the paths and scales) simple. And once that’s done, the rest is pretty simple to go about.
Check back in a few weeks or even days, I’ll be writing about adding a brush with React and D3 to a bar chart so that only data within a specified domain can be retrieved or something similar about React and D3.
Thank you for reading, I hope this gives you an idea about how React and D3 work together to create custom data visualizations.
Claps and shares are very much appreciated!
I have a keen interest about data visualization with React and D3. If you follow me on Twitter, I won’t waste your time. ?
Published at Mon, 06 Jan 2020 06:30:07 +0000
{flickr|100|campaign}
