Getting Started with D3.js and React

Learn via video courses
Topics Covered

Overview

Developers may produce interesting, reusable data visualizations like area charts, bubble plots, and line graphs using React and D3.js, two JavaScript tools. Although frontend developers love coupling React and D3, it might be difficult to use the two tools together. We will cover how to utilize D3 in React, go through why you should use D3, and show you how to make a chart in React using D3 in this article.

What are D3.js ?

With HTML, CSS, and SVG, dynamic, interactive data visualizations may be made using the JavaScript library D3.js. D3 allows you to alter visualizations by changing the data because it connects data to the DOM and its elements. D3.js v7.7 represents the most latest release as of this writing.

While D3's emphasis on web standards allows you to take full advantage of contemporary browsers without being constrained by a proprietary framework, D3.js and React are frequently used in tandem to create dynamic data visualizations.

React is a frontend Js toolkit that is free to use and open source for creating complex user interfaces and UI components. It is a declarative, effective, and flexible framework that enables you to create intricate user interfaces from basic, reusable parts. These elements are able to keep their condition on their own.

Why Should You Use D3.js?

JavaScript packages called React and D3.js allow programmers to create scalable, adaptable, and visually appealing data-driven user interfaces. These libraries were used to create Trading Robo-Advisor, one of Grid Dynamics' research and development initiatives. It is a software-based product created for automated asset management and investment decisions that are primarily made using algorithms with little to no human interaction.

For JavaScript developers, implementing dynamic modernized Web pages and large dataset visualization are equally valuable. Utilizing shapes, lines, and colors, data visualization enables you to present information clearly and effectively. There are several data visualization tools on the Web, but D3.js is the de facto option for data visualization in JavaScript thanks to its widespread adoption by front-end developers.

With the use of animations and other captivating elements, you may encourage user involvement with the lightning-fast, large dataset, and dynamic behavior support of D3.js. By using forms, lines, interpolation, and other design elements, developers can create detailed, comprehensive, and scalable visual data representations. D3.js is a good choice because of these qualities if you need to create charts that lack specific designs or animations, a wide range of options, or unique handlers that the ready-to-use chart library can offer.

  • Everybody Uses It: For JavaScript developers, implementing dynamic modernized Web pages and large dataset visualization are equally valuable. Even better, you may browse through carefully curated collections of incredible D3.js examples at your leisure on GitHub.
  • Highly Desirable Skillset : D3.js is utilized for a dizzying array of applications, therefore it goes without saying that having experience with it is a plus when applying for jobs in the programming and development fields.
  • Fantastic Community : Excitingly, this brings up a fantastic advantage D3.js has. Like other open-source programming languages, this one is open-source, so the community is just as helpful and active. Over 9,000 community forks of D3.js have been made, and there is a tonne of free extension resources and third-party wrapper libraries to make the time you spend making visualizations in D3.js even simpler and more flexible.
  • Unmatched Flexibility: You can pretty much display data as you want with D3.js. Looking to visualize where Lebron James shoots from on a half-court model of a basketball court? It was completed. Even better, the code is accessible via Github. Your creativity and your skill to work with D3.js to realize your concept are the only boundaries.
  • Low-Key Web Development Skills: Low-Key Web Development Skills: You came to learn D3.js so you could create beautiful charts and visuals, but you left with only the bare minimum of JavaScript and HTML5. Because D3.js must be created from scratch, you become familiar with the syntax used in these programming languages, thereby slaying three birds with one stone. Learning how to display items on a webpage is made possible by D3.js' manipulation of elements on the document object model.

Using D3.js Inside a React App

Because both frameworks desire to manipulate the DOM, combining D3.js and React might be difficult. Both of them exert influence over UI elements, though in distinct ways.

Start a new react project

We're going to utilize the Cutilizeeact App boilerplate to set up React. You can reuse it by installing it globally on your local system by running the following code :

The create-react-app template will then be used to construct a new app. Use React's most recent version, which is version 18 as of this writing. Feel free to rename the react-d3 directory in your project to something else :

Change the directory in the newly created project :

Setting Up D3.js

As illustrated below, you may install the D3.js library using npm or the CDN to add it to your app. This will, as anticipated, install D3.js version 7.7, which is the most recent stable version :

We can now start utilizing D3 with React to build data visualizations. Run the following code to view the recently constructed app in your default browser :

When tinkering with the code, the aforementioned command will also make it possible for the web application to be hot-reloaded.

Create a Bar Chart Component

Components are the building pieces that React employs to create user interfaces. As a result, you should model your D3.js chart as a component that can be applied to various areas of your website.

Example

Create a new file called src/BarChart.js to accomplish this. Add the following boilerplate to this file.

Create a Custom Hook to Use D3js

Built-in hooks make it simple to break down reusable code snippets into smaller functional pieces. For example, useState and useEffect manage component state and side effects, respectively (useEffect combines numerous lifecycle methods into a single hook). They act as the cornerstones for creating unique hooks. Components can be made lighter, more flexible, and more manageable as a React application expands and becomes more complicated to accommodate new features by creating them as functional components and assigning shareable functionality to custom hooks.

The same guidelines apply to custom hooks as they do to built-in hooks :

  • They have to be invoked at the top level of a custom hook or React functional component. They cannot be used in nested functions, conditionals, or loops.
  • They have to be used in a custom hook or a React functional component.

Example

As a starting point in the previous phase, you rendered an svg element using conventional JSX. From here, you can use the useRef and useEffect hooks to connect D3.js with the newly formed svg element and set the timing of your D3.js function's execution.

You should name your new hook useD3, as hooks typically start with that prefix. Add the following method to a new file in the src/hooks/useD3.js directory.

The hook function takes two arguments :

  • The callback renderChartFn includes the D3.js code that will be run. *Dependency is a fixed-length array used by React to specify the timing of renderChartFn execution.

This helps avoid updating and re-rendering the chart without necessity.

Using the Custom Hook in the BarChart Component

Since React hooks are merely functions, your BarChart component can simply call them. Below is a demonstration of a new BarChart component that makes use of the react hook discussed.

Example

By giving the hook two arguments and connecting the ref that is returned by the hook to the svg element, the code below uses the hook.

Mike Bostock's Bar Chart Sample served as the inspiration for the first argument given to the useD3 hook. The data variable from the component's props is joined to the chart elements in the code excerpt above. Keep in mind that the function does not utilize directly. Since the chart render function can be called multiple times, we wish to prevent the creation of duplicate elements by using the append method. Instead, it decides which elements should be added, deleted, or changed using selection joins.

React examines the dependency array provided as the second argument to determine whether the chartRenderFn needs to be called again. In this instance, [data.length] is used. If data items are added or withdrawn, React will update the chart as a result. You might notice that your method is called too frequently if you simply send the complete data array [data] to the dependents parameter. This is because React just superficially compares each element in the dependents array by default. You might need to substitute a content hash or last-updated time stamp for this parameter in other circumstances where data items are being modified for your chart to be correctly updated.

Using Your New BarChart Component

A BarChart component has been produced by you. It renders a BarChart using data as props. To use it, alter your src/App.js file like follows:

Example

This code snippet binds to your BarChart component using static data from a JavaScript variable.

Adding Labels to a Bar Chart

Add the following code to the drawChart function to add labels :

Example :

Similar to what we did for the bars, except that this time text is added. Now, the bar chart ought to resemble the following :

d3 react1

D3.js and React bar chart with labels Hence the code will be as follows :

Example :

How to Make a Chart Reusable in React and D3.js

Making reusable components is one of the most crucial React principles. We must separate the BarChart component from the data and make it a parameter in order to achieve this. The dependencies on constants, such as the graph's height and width, will all be eliminated as a result of this. We'll employ the props mechanism in this case.

We will now alter App.js so that the BarChart component can receive the parameters :

Coherently, we change their usage in the BarChart component. They will be accessible in the props object in the source code for BarChart.js :

From the code block below, the width and height attributes become, respectively :

In our React app, we can reuse the bar chart in any location this way.

Conclusion

  • D3 allows you to alter and visualize the data because it connects data to the DOM and its elements.
  • JavaScript packages called React and D3.js allow programmers to create scalable, adaptable, and visually appealing data-driven user interfaces.
  • With the use of animations and other captivating elements, you may encourage user involvement with the lightning-fast, large dataset, and dynamic behavior support of D3.js.
  • We can create Custom Hook to use D3 js.
  • D3.js and React are frequently used in tandem to create dynamic data visualizations.