Bars Icon

Recharts: Intro to JavaScript charting

29-12-2023 11:59 AM

The JavaScript ecosystem includes many charting libraries, but it’s tough to create a full-featured charting API that performs well in real-world usage. This article is a hands-on introduction to one of the good ones. Recharts is a React-specific incarnation of D3, a well-vetted framework. To test it out, we’ll use price and volume data for cryptocurrencies.

To set up our project, we’ll use create-react-app. You should already have Node/NPM installed. Once you do, you can type: npx create-react-app crypto-charts. Once that is finished, you can move into the /crypto-charts directory and add the required dependency with: npm install recharts.

Next, we’ll use fetch to load the data from the CoinGecko API and then display it. We’ll get a screen like this one:

To load and display the data, just put the following code into the project’s src/App.js file and run the application with npm start.

This code is intentionally very simple so we can make sure the API is loading the data properly. We just output it to the screen with JSON.stringify(). Notice that we’re using the bitcoin endpoint.

Next, let’s plug the price data from the response into a simple line chart, as showin in Listing 2. I’m only showing the parts of the code that are different from Listing 1.

The key updates here are importing the Recharts components, creating the cryptoData state variable hook, defining the <LineChart> markup, and plugging the cryptoData state into it. In just seven lines of markup, we’ve got a pretty nice looking and functional chart. Besides the LineChart component itself, which consumes the cryptoData variable as its data prop, we have several nested children that help define the chart layout, including XAxis, YAxis, Tooltip, Legend, and Line.

The XAxis and YAxis components tell the chart how to handle the axes. In this case, we handle the formatting of the “ticks” with a simple time formatter, since the X axis is the timestamps. The dataKey property tells the axis how to find its value, which is the first element of the array, 0. The YAxis has no properties and uses the defaults. The Tooltip formatter is what drive the data you’ll see when you mouse over the line. Legend sets the styling for the legend and the Line component sets the styling on the line itself.