A Comprehensive Guide to Using D3.js in React
By
Charles Mahler /
Use Cases
Jan 18, 2023
Navigate to:
One of the most flexible and powerful ways to visualize data is through D3.js. As a React developer, you can use Data-Driven Documents (D3) to enhance the presentation of your applications that take advantage of data.
This guide will show you how to use D3.js and React to create interactive and dynamic data visualizations. We’ll then review the steps to create a simple bar chart using React and D3.js.
By the end of this tutorial, you’ll better understand how to use D3 and React to create interactive data visualizations.
What is D3.js?
D3.js is a JavaScript library that data scientists and developers can use to create interactive and dynamic visualizations. You can use it to create various charts and graphs, such as network diagrams and bar charts.
With D3.js, developers can create customized charts and graphs tailored to their needs. It has a flexible API that allows them to create rich and interactive visualizations. Its built-in features include support for rendering to SVG and canvas elements, interaction, and animation.
Now data scientists and developers can quickly create informative and engaging charts and graphs to help make complex data easier to understand.
How popular is D3.js?
D3.js is a popular JavaScript library used for data visualization. It ranks among the top-100 most-starred repositories on GitHub. Companies such as Accenture, Coinbase, and Coursera use it as part of their stack. Overall, it’s a vital part of the data visualization industry.
Does D3.js work with React?
Yes, you can use D3.js and React to create interactive visualizations. React’s various advantages make it an ideal choice for creating data presentations. Its ability to build interactive and complex UIs using minimal code is a major advantage. This is especially useful for creating data visualizations, where you can create various components with their own appearance and behavior.
The D3.js API is flexible and powerful, making it an ideal choice for developers who want to create custom visualizations. With React and D3.js, you can create engaging and powerful data presentations and enjoy a number of benefits, including better reusability and maintainability.
How can I use D3.js in React?
This guide assumes that you have Node.js installed. If not, you can follow this link. Below are the steps you can follow to get started with D3.js and React.
Initialize your app and install D3.js
First, you’ll create a React app using npx.
npx create-react-app example-d3
Then you’ll switch to your created app and install D3.js like this:
cd example-d3
npm install d3
Create a React component
After installing the D3.js library, the next step is creating a component. This component should also include the imports.
Why use useRef Hook?
The useRef hook allows you to store a reference to a DOM element. You’ll use this hook to store a reference to the D3.js visualization, allowing you to access and manipulate it from within the component.
Use useState Hook
You can use this hook to store data related to the visualization, such as the data being visualized, and update the visualization when the state changes.
Use useEffect Hook
You can use the useEffect hook to perform side effects on a React component. You can do this by setting the position and size of the elements in the component. It can also create a D3.js visualization that shows the changes in the component’s state.
Creating a Bar Chart
To create a bar chart using React and D3, you can use the D3.js library to create the chart structure, then use React to create the svg elements and render the chart to the page.
Here is an example of how you might create a bar chart using React and D3:
import React, { useState, useEffect } from "react";
import * as d3 from "d3";
const BarChart = () => {
const [data, setData] = useState([
{
name: "A",
value: 50,
},
{
name: "B",
value: 20,
},
{
name: "C",
value: 40,
},
{
name: "D",
value: 70,
},
]);
useEffect(() => {
const margin = { top: 20, right: 20, bottom: 30, left: 40 };
const width = 960 - margin.left - margin.right;
const height = 500 - margin.top - margin.bottom;
const x = d3.scaleBand().range([0, width]).padding(0.1);
const y = d3.scaleLinear().range([height, 0]);
const svg = d3
.select(".bar-chart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(
data.map(function (d) {
return d.name;
})
);
y.domain([
0,
d3.max(data, function (d) {
return d.value;
}),
]);
svg
.selectAll(".bar")
.data(data)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", function (d) {
return x(d.name);
})
.attr("width", x.bandwidth())
.attr("y", function (d) {
return y(d.value);
})
.attr("height", function (d) {
return height - y(d.value);
});
svg
.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
svg.append("g").call(d3.axisLeft(y));
}, [data]);
return ;
};
export default BarChart;
We use the useRef hook to create a reference to a div element that we’ll use to render the chart. Then, in the useEffect hook, we use D3 to create an svg element and append it to the div. We then use D3 to bind the data to the svg elements and render the chart.
With the data defined, we can now use D3.js to create the bar chart. To do this, we must define a few scales and axes to map the data to the svg element. We’ll use a linear scale to map the population data to the height of the bars and an ordinal scale to map the country names to the x-axis. We’ll also define a set of axes to display the data on the chart.
Next, we’ll use the d3.select method to select the svg element. Then we’ll use the .selectAll and .data methods to bind the data to the svg element. We’ll then use the .enter method to create a set of rect elements representing the chart’s bars. We’ll set the x and y attributes of each rect element using the scales and axes we defined earlier, and we’ll also set the width and height attributes using the data values.
Creating a Line Chart
This is how you can use D3.js to create a line chart:
import React, { useRef, useEffect } from "react";
import {
select,
line,
curveCardinal,
scaleLinear,
axisBottom,
axisLeft,
} from "d3";
//data
const data = [
{ x: 0, y: 10 },
{ x: 1, y: 20 },
{ x: 2, y: 15 },
{ x: 3, y: 25 },
{ x: 4, y: 30 },
];
//chart component
const LineChart = () => {
//refs
const svgRef = useRef();
//draws chart
useEffect(() => {
const svg = select(svgRef.current);
//scales
const xScale = scaleLinear()
.domain([0, data.length - 1])
.range([0, 300]);
const yScale = scaleLinear().domain([0, 100]).range([100, 0]);
//axes
const xAxis = axisBottom(xScale).ticks(data.length);
svg.select(".x-axis").style("transform", "translateY(100px)").call(xAxis);
const yAxis = axisLeft(yScale);
svg.select(".y-axis").style("transform", "translateX(0px)").call(yAxis);
//line generator
const myLine = line()
.x((d, i) => xScale(i))
.y((d) => yScale(d.y))
.curve(curveCardinal);
//drawing the line
svg
.selectAll(".line")
.data([data])
.join("path")
.attr("class", "line")
.attr("d", myLine)
.attr("fill", "none")
.attr("stroke", "#00bfa6");
}, [data]);
return (
<svg ref={svgRef}>
</svg>
);
};
export default LineChart;
The useRef hook references an element we’ll use to render the chart. The useEffect hook appends the element to the variable. D3 creates an svg element and passes the data to the line generator. We then apply a path element to the svg to set the d attribute and render the line.
Inside the useEffect hook, the select() method from D3 is used to select the svg element and create a selection. This selection is then used to draw the chart.
We’ll create the scales using the scaleLinear() method from D3. Then we use the xScale to map the data points to the width of the svg element. The yScale maps the data points to the height of the svg element.
Next, we create axes using the axisBottom() and axisLeft() methods from D3. The xAxis displays the x values on the x-axis and the yAxis on the y-axis.
The line() method from D3 plots the points, creating a continuous line. This line generator is used to create a path from the data points. The curveCardinal() method is used to smooth the line.
Finally, the line is drawn using the selectAll() and join() methods from D3. The join() method is used to draw the line with the data points, and the selectAll() method is used to select all elements with the class. We then set the attributes of the line, such as “fill,” “stroke,” and “d”.
Conclusion
D3 is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG, and CSS. D3’s emphasis on web standards gives you the full capabilities of modern browsers without tying yourself to a proprietary framework, combining powerful visualization components and a data-driven approach to DOM manipulation.
Where React is focused on organizing your web application into views with specific data needs, D3 enables you to easily create attractive visualizations and browser-based graphics using relatively simple code.
Now that you know how to use D3.js and React, why not try? Start small and experiment with the different features available to you. You may be surprised by what you can create! There’s no better way to learn than by doing.