Original text: blog.logrocket.com/data-visual…

D3.js is used for data visualization in React

Data visualization refers to the technology of using visualized objects such as charts and graphs to communicate data in a clearer and more efficient way.

On the Web, there are many libraries available to visualize data, but the most prominent is the D3js library. It has become a fact of life for data visualization and has earned the trust of many developers.

React is a library used by many developers. In this article, you’ll learn how to use React and D3 to create reusable and beautiful components.

First, let’s take a brief look at these libraries.

React

React is a JavaScript library for building user interfaces. It makes it easy to create reusable components that can be combined to form more complex components.

These components can maintain their own state.

D3

D3.js is a JavaScript library based on data manipulation documents. It uses HTML, CSS, and SVG to bring data to life.

D3 attempts to provide a way to efficiently manipulate data based on data, rather than providing a framework to accomplish all possible functions.

D3 is fast, supports large data sets and dynamic behavior for animation and interaction.

Let’s see how you can use these two libraries together to create dynamic data visualization components.

Install the React

The easiest way to install React is to use the React team’s create-react-app template. To install globally on the local machine so it can be reused, run the following command on the terminal:

npm install -g create-react-app
Copy the code

Next we create a new app using the create-react-app template

create-react-app react-d3
Copy the code

Enter the new project catalog below

cd react-d3
Copy the code

Install the D3

You can add the D3 library to your application using CDN or through an NPM installation

In this case, we use NPM to install:

npm install d3
Copy the code

Now that the preparation is complete, we can use D3 in React for data visualization.

To preview the created application on the default browser, run the following code:

npm start

Copy the code

Create a chart using D3

Use your favorite editor (I used vscode) to open the project and open the file SRC/app.js.

This is the component that is currently rendered in the browser. We need to remove the render() method content and replace it with our own content.

Create a barchart.js file in the SRC directory to create our BarChart.

Add the following code to the file:

import React, {Component} from 'react';
import * as d3 from "d3";

class BarChart extends Component {}export default BarChart;

Copy the code

We’ll use the ComponentDidMount lifecycle method to display the BarChart when the BarChart component has been loaded into the DOM.

Add the following to the BarChart component:

class BarChart extends Component {
    
  componentDidMount() {
    this.drawChart(); }}Copy the code

We will finish drawing D3 in the drawChart method.

Normally, when using D3 without React, you don’t have to put D3 code into the method, but this is important in React to ensure that the diagram is displayed only when the component is mounted to the DOM

Next, we create the drawChart method:

drawChart() {
  
  const data = [12.5.6.6.9.10];
    
  const svg = d3.select("body").append("svg").attr("width".700).attr("height".300);
  
}

Copy the code

What does this method do?

First, we define a variable, data, that contains the data we want to visualize.

Second, we defined an SVG using the D3 approach. We used SVG because it is scalable, meaning that no matter how big the screen is, or how much you zoom in to view the data, it will not appear pixelated.

D3.select () is used to select HTML elements in the document. It selects the first element that matches the pass parameter and creates a node for it.

In this case, we passed the body element, which will be changed later to make the component more reusable.

The append() method appends an HTML node to the selection and returns a handle to the node.

The attr method is used to add attributes to elements. This can be any attribute you normally add to an HTML element, such as class, height, width, or fill.

We then add an SVG element to the body element with a height of 700 and a width of 300.

Under the SVG variable we created, add the following code:

svg.selectAll("rect").data(data).enter().append("rect")

Copy the code

Like the select method, selectAll() selects the elements that match the arguments passed to it. Instead, selectAll() selects all elements that match the argument, not just the first one.

The data() method is used to append data to the selected HTML element.

Most of the time, these elements won’t be found because most visualizations deal with dynamic data, and it’s nearly impossible to estimate the amount of data to represent.

The Enter () method saves us from the bottleneck because it is used in conjunction with the Append method to create the missing node and still visualize the data.

So far, we have created nodes for each data point. All that’s left is to make it visible.

To make it visible, we need to create a column for each dataset, set a width, and dynamically update the height of each column.

The attR method allows us to use callbacks to process dynamic data:

selection.attr("property", (d, i) => {}) 

Copy the code

Where d is the point value and I is the index of the data in the array.

First, we need to set each data point at a specific point on the X-axis and Y-axis of the bar chart

First, we need to set each data point at a specific point on the X-axis and Y-axis of the bar chart. We do this using the “X” and “y” attributes, where “X” represents the position of the rod along the X-axis (horizontal) and “y” represents the position of the rod along the Y-axis.

In addition, we need to set the width and height of each data point. The width of each data point is constant because the width of the bar graph is the same.

Height, on the other hand, depends on the value of each data point. We must use the callback function to make the bar graph show the value of each data point.

We changed the SVG variable to:

svg.selectAll("rect")
  .data(data)
  .enter()
  .append("rect")
  .attr("x", (d, i) => i * 70)
  .attr("y".0)
  .attr("width".25)
  .attr("height", (d, i) => d)
  .attr("fill"."green");
  
Copy the code

For “x”, each index of the data point in the array is multiplied by a constant integer 70, moving each bar by 70.

Y has a constant y, which we’re going to change very quickly.

The width also has a constant value of 65, less than the position of each element in the diagram, thus creating a space between each element.

The height of the bar depends on the value of each item in the dataset.

Using it, we created a bar chart. However, we have two problems:

  1. The bar chart in the chart is small
  2. The chart is also upside down

To solve the above problem, we multiply each data by a constant, such as 10, to increase the size of each bar without affecting the data:

.attr("height", (d, i) => d * 10)

Copy the code

Next, we’ll address the inverted bar chart problem, but first, let’s understand why the chart is inverted.

SVG positions start from top to bottom, so use the Y attribute 0 to place each bar at the top edge of an SVG element.

To solve this problem, we subtract the height of each bar from the height of the SVG element:

.attr("y", (d, i) => h - 10 * d)

Copy the code

Where (10 times d) is the height we calculated before.

Taken together, the BarChart component will be:

class BarChart extends Component {
  componentDidMount() {
    this.drawChart();
  }
    
  drawChart() {
    const data = [12.5.6.6.9.10];
    
    const svg = d3.select("body")
    .append("svg")
    .attr("width", w)
    .attr("height", h)
    .style("margin-left".100);
                  
    svg.selectAll("rect")
      .data(data)
      .enter()
      .append("rect")
      .attr("x", (d, i) => i * 70)
      .attr("y", (d, i) => h - 10 * d)
      .attr("width".65)
      .attr("height", (d, i) => d * 10)
      .attr("fill"."green")
  }
        
  render(){
    return <div id={"#" + this.props.id} ></div>}}export default BarChart;

Copy the code

Now we have a basic bar chart. Let’s do a little bit more, add labels.

Add labels to bar charts

To add labels, we add the following code to the drawChart function:

svg.selectAll("text")
  .data(data)
  .enter()
  .append("text")
  .text((d) = > d)
  .attr("x", (d, i) => i * 70)
  .attr("y", (d, i) => h - (10 * d) - 3)
  
Copy the code

This is similar to what we did with these bars, but this time, text is appended.

The bar chart should look something like this:

Build reusable bar charts

An important part of React is making components reusable.

To do this, we need to remove the supplied data and pass it to the component via props.

The width and height of SVG will also be passed through items:

const data = [12, 5, 6, 6, 9, 10];

Copy the code

To:

const data = this.props.data;

Copy the code

Width and height attributes are made up of:

const svg = d3.select("body").append("svg").attr("width", 700).attr("height", 300);

Copy the code

To:

const svg = d3.select("body").append("svg")
  .attr("width", this.props.width)
  .attr("height", this.props.height);
  
Copy the code

In the app.js file, we can now use the component and pass the data we want from the parent:

class App extends Component {
  
  state = {
    data: [12.5.6.6.9.10].width: 700.height: 500.id: root
  }

  render() {
    return (
      <div className="App">
        <BarChart data={this.state.data} width={this.state.width} height={this.state.height} />
      </div>); }}Copy the code

This way, we can reuse bar charts anywhere in our React application.

Thanks !!!!!!!

Original text: blog.logrocket.com/data-visual…