Create charts with React and D3

This article is translated from:
https://dzone.com/articles/charts-with-modern-react-and-d3

This article will introduce how to use D3JS and ReactJS to create basic charts.

ReactJS is a front-end JavaScript library for making reusable web components. Its idea is to decompose Web Applications (and mobile applications) into smaller, independent and reusable components (through React Native). It makes it much easier to develop and maintain medium to large web applications.

D3JS is a data-based JavaScript graphics library. It can help bind data to HTML elements (SVG) and manipulate HTML elements with that data. You can use it alone (without using ReactJS or any other web framework) to create almost any data visualization tool and dashboard. However, if you combine it with ReactJS, you can create a modern data dashboard based on Web.

In this article, I will show you how to create basic diagrams using the functions of D3JS and ReactJS. Later, I will continue to show how to completely customize the chart and add more information and interaction. Now keep it simple. Let's enter the world of data reporting and visualization.

Before visualizing the data, we need to pass the data to the application. Real life applications are most likely to complete this operation through API calls to the server, so as to provide data to the application (usually in JSON or XML format).

In the application program I exemplify here, the data is stored on the local computer. I will use the Node JS http server to serve it to simulate real API calls. Http server is a quick way to set up the server to provide static files. All I have to do is create a folder (named covid data), store the data file (named covid data. CSV), and then run the following command:

npx http-server --cors

Note: - CORS allows us to make requests from the (React) application to the server (HTTP server) on the same computer. If this flag is deleted, all requests will be rejected according to CORS policy.

Now we have run the server and can provide data. So you can start creating front-end applications using React and D3.

The best way to create a React app is to use the Create React App:

npx create-react-app react-d3

It will take several minutes to complete this command. It will create a new directory called react-d3 and create a basic React application in it. When finished, change the directory and start the application:

Cd react-d3
Npm start

Here, the new React app is ready for use on port 3000. You just need to start the browser and make sure it works by visiting the following link:

http://localhost:3000

You will see the React welcome page.

Now, all we need to do is start the project.

First, let's try to change the welcome page of React. Open Src / APP JS, delete everything and replace it with:

import React, { useEffect } from 'react';
import './App.css';
import draw from './draw'
function App() {
  useEffect(() => {
    draw()
  })
  return (
    <div className="App">
      <h1>D3 Simple Bar Chart</h1>
      <div id="chart-container"></div>
    </div>
  );
}
export default App;

In the return method, we added a div with id "chart component". We will use D3 to add a chart here.

We also use a hook called "useEffect", which is basically equivalent to "componentDidMount" and "componentDidUpdate" in class components. In this hook, we run the "draw" function, which will run all D3 commands we need to draw the chart. Of course, you can also get data from the API, but here we use D3 to complete data processing in the draw function.

So far, React has completed the infrastructure we need to create charts. Now, let's look at how to use D3 to get data and chart.

Create a file in the src folder, name it "draw.js", and then put the following code in it:

import * as d3 from 'd3'
async function draw () {
  const width = 800
  const height = 500
  const marginTop = 30
  const marginRight = 30
  const marginBottom = 30
  const marginLeft = 50
  const numOfCountries = 10
  const title = "COVID-19 Death Count"
  const svg = d3.select('#chart-container')
    .append('svg')
    .attr('width', width)
    .attr('height', height)
    .style('background-color', '#D3D3D3')

  svg.append('text')
    .attr('x', (marginLeft + width + marginRight) / 2)
    .attr('y', marginTop / 2)
    .attr('dy', '0.33em')
    .text(title)
    .attr('text-anchor', 'end')
  const dawData = await d3.csv('http://127.0.0.1:8080/covid-data.csv')
  const data = dawData.filter(d => d.date === "2020-04-11" && d.location !== "World").sort((a, b) => b.new_deaths - a.new_deaths).filter((d, i) => i < numOfCountries).map(d => ({date: d.date, location: d.location, new_deaths: +d.new_deaths}))
  console.log(data)
  const xScale = d3.scaleBand()
    .domain(data.map(d => d.location))
    .range([marginLeft, width - marginRight])
    .padding(0.3)
  const xAxis = d3.axisBottom()
    .scale(xScale)

  svg.append('g')
    .attr('transform', 'translate(0,' + (height - marginBottom) + ')')
    .call(xAxis)

  const yScale = d3.scaleLinear()
    .domain([0, d3.max(data, d => d.new_deaths)])
    .range([height - marginBottom, marginTop])

  const yAxis = d3.axisLeft()
    .scale(yScale)

  svg.append('g')
    .attr('transform', 'translate(' + marginLeft + ', 0)')
    .call(yAxis)

  svg
    .selectAll('rect')
    .data(data)
    .enter()
    .append('rect')
    .attr('x', d => xScale(d.location))
    .attr('y', d => yScale(d.new_deaths))
    .attr('width', xScale.bandwidth())
    .attr('height', d => height - marginBottom - yScale(d.new_deaths))
    .attr('fill', 'yellow')
}
export default draw

I'll explain the code line by line.

Line 1 imports all d3 methods.

In line 3, we define a draw function. And in the following line 67, we will export this function so that it can be used in app JS file.

In lines 5 to 12, we define all constants for the appearance and functionality of the chart.

In lines 14 to 18, we select the div with id "chart component" (created in the "App.js" file), add SVG elements to it, and set its width, height and background color.

In lines 20 to 25, we add the title to SVG and place it in place.

In lines 27-29, we use D3 Call the CSV method to get the data through the API. Then, we filter, sort and reorganize them and record them to the console so that we can view the data and ensure that it meets expectations. Later, we may delete line 29 before putting it into production (even if we don't, React will automatically delete all console.logs when building the production version of the application).

In lines 31-34, we use d3's extremely useful scale method (scaleBand in this case) to define the X scale so that we can convert the data points into real points at the correct position on the chart.

Then, in lines 36-37, we define an axis, and in lines 39-41, we connect this axis to SVG. In lines 43-52, perform exactly the same operation for the Y axis.

Finally, in lines 54-63, we select all bars (rectangles) on SVG (which is an empty set so far) and attach the data to the bar. For these data points, we attach a new bar to SVG. Then, we adjust the x, y, width, height and fill color of each bar.

this is it. This is a very simple chart created with D3 and React. Of course, it lacks many functions and cannot interact, but we can add it later. The purpose of this article is to show you how easy it is to create simple charts using D3 and modern React.

(end)

Tags: React D3

Posted by Obsession on Thu, 05 May 2022 16:21:35 +0300