DEV Community

Gil Fink
Gil Fink

Posted on • Originally published at gilfink.Medium on

Integrating D3 in Qwik Apps

In the past I wrote a bunch of posts that explained how to integrate D3 library and React. In this post I’ll do the same but this time I’ll show you how to integrate D3 in Qwik apps. We will build together a D3 tree and host it inside a basic Qwik app.

Are you ready?

Things to do before you start adding the suggested code:

  1. Create a new Qwik app using the npm create qwik@latest .

  2. Add a new route to your app, which will be used to show the D3 graph.

Creating a Qwik D3 Container Component

First you are going to add a new TreeContainer component. This component will be responsible to hold the D3 container, which will be used to create the graph.

Let’s look at the code:

The TreeContainer is going to be the div that D3 will use to create the graph. You use a signal to reference the rendered div , so you will be able to use it’s in-memory Html element representation later on.

Another thing that you can notice is the usage of useVisibileTask$. Since D3 runs only in the client, you should use the useVisibileTask$ hook that makes sure that the code which is responsible to creates the graph runs after the component’s client rendering.

Building the Graph Generator

Once the container is ready it’s time to write the createGraph function.

Here is the full function code:

Let’s analyze the code to understand what is going on. We will start in the beginning with the processSymbols function.

Sometimes we have a model that doesn’t fit into the way the D3 graphs expect their data. The processSymbols function will transform the symbols array to the needed graph representation.

At the start of the createGraph function you set the d3 tree in-memory implementation. This is happening in these lines of code:

Then, you create the tree visual representation using D3 API that creates SVG elements such as paths, circles, text and more:

The data that is being used in the example is the following symbols array:

After you wire everything you can run the app to see the following graph on your screen:


Symbol Graph

Summary

In the post I showed you how easy it is to integrate D3 in Qwik apps. The post guided you how to create the graph container and then how to create the graph by using D3 functionality.

You can take a look at the whole example in the qwik-d3-example repository.

Top comments (0)