React + D3.js = ❤️
A love story – So
simple powerful yet so complicated
Since then, React became the most popular framework to build user interfaces. This rose a question: how to build a chart in react? That's a complicated question with many answers. Here are the 3 most common approaches.
3 ways to draw a chart in react
→ 1️⃣ Charting libraries
There is a myriad of charting libraries offering react components for every chart type. HighChart, ReCharts, React-viz, plot, visX and so many more. Those libraries are awesome: you'll get a working chart in minutes using them.
But simplicity comes with a cost: the time you saved in the first place will be lost when you'll try to reach a high level of customization.
If you want to build something unique, you need to draw shapes one by one.
→ 2️⃣ D3 for rendering in a
Basically, you can create a
div in the DOM using react. You can then use the drawing methods of the d3-selection module like
axisBottom to target this
div, and add the content of the chart.
Let's apply this to draw axes:
You can use all the d3 knowlege you have in a useEffect hook to build the graph in a react context.
This works but comes with some caveats. To put it in a nutshell you now have 2 tools trying to control the DOM: react and d3. That's hard to maintain for large applications.
→ 3️⃣ D3 for maths, React for rendering
This gallery suggests using d3.js only for the math utils it provides. And to add entries to the DOM using react, like for any other UI element.
Let's say we want to build a scatterplot. The
scaleLinear function of d3.js is used to build the scales. Now that we can easily know the position of a circle on the screen, we can just loop through all data items and render them as a
circle svg element.
Use d3.js to compute the scales. Use React to render the circles.
Learn concepts, Get templates
This gallery is all about using the power of the d3 math utils and the react rendering engine.
The first goal is to teach the concepts. Many examples are provided for each chart type. Each one targets a specific theme like color, axis, responsiveness, hover effect, or tooltips.
The second goal is to provide templates for each viz type. Building a viz from scratch is time-consuming, so better tweak an existing example.
All graph examples come with an explanation and a code sandbox allowing you to play with the code.
I built this website with ❤️. I hope it will help you create stunning vizs in a minimum amount of time. Reach me on Twitter, contribute on github and subscribe to the newsletter to know when new chart types are published!