Integrating D3.js to a Typescript React Application

Krasnoff Kobi
Geek Culture
Published in
2 min readMay 2, 2021

In today's front-end application development, the ReactJS library has become the most popular Javascript/Typescript framework.

On the other hand, D3.js is the most commonly used Javascript library for creating dynamic charts on the Web.

Integrating the two frameworks and more than that using the Typescript language can be a bit tricky. But it is absolutely possible. That is the purpose of this article.

Create and install the libraries

First of all, we will have to create a new react project. If we choose the Typescript language then it is recommended to define a Typescript template. This is done by the following NPM command:

npx create-react-app react-ts-chart — template typescript

The next step is not mandatory but it is recommended if you want to use Sass precompiler for your project:

npm install node-sass — save

Now, Let import the D3.js library. The first line is the D3.js files and the second line is for the Typescript definitions:

npm i d3npm i @types/d3

That will be enough for creating our first graph.

Creating our first page

Let's create our first page containing our first graph. A basic Typescript template will look something like this:

D3 Principles

D3 is a javascript framework that illustrates its graphs on an SVG element. So we will have to define such an element. First, let’s define an SVGSVGElement object:

ref!: SVGSVGElement;

and link it to an SVG element:

<svg className=”container” ref={(ref: SVGSVGElement) => this.ref = ref} width=’100' height=’100'></svg>

now let’s import the D3.js library to our component:

import * as d3 from ‘d3’;

For this tutorial, we will implement a very simple bar graph, the data will be a simple hardcoded Number array. Let’s build a private function that illustrates the graph:

In a React component, there are several life cycle stages. One of them the componentDidMount() function. This stage executes after the constructor and the render (in this stage you actually draw the HTML) stages. So let’s execute the buildGraph function on the stage.

The final component should look something like this:

Now let’s design our new graph by an SCSS template:

Our new graph should look something like this:

Conclusion:

Congratulations! we have made our first step toward implementing graphs and charts to our react applications.

The full source code can be found at: https://github.com/krasnoff/react-ts-chart

--

--