Integrating D3 in Qwik Apps

Gil Fink
2 min readJun 30, 2023

--

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 its in-memory Html element representation later on.
Another thing that you can notice is the usage of useVisibileTask$. D3 only works in the user’s browser, not on the server. Therefore, you should use the useVisibileTask$ hook in your code. This hook ensures that the part of your code responsible for creating the graph is executed after the component renders in the client side.

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.

--

--

Gil Fink
Gil Fink

Written by Gil Fink

Hardcore web developer, @sparXys CEO, Google Web Technologies GDE, Pro SPA Development co-author, husband, dad and a geek.

No responses yet