Creating SVG Line Chart with Preact

An 80 KB library to do the job of few lines of code.

Around 2 years ago, I needed a chart for a dashboard of a project I was working on. So, I searched for charts libraries and I found a plenty of them, but the problem is that most of them were not really what I had in mind. Either they’re too big ≈80 KB, or I have to change my data structure in someway to match their API, or they don’t have that set of flexible enough features, but I used one of them anyway.

After a while, when I saw the power of SVG and how it can be used in the most simple ways to create amazing stuff, I thought why don’t I create my own chart by myself.

At the same time I was reading a lot of tweets about Preact and how it’s the 3KB alternative of React. So, I said why don’t I create my SVG chart with Preact and hit two birds with one stone.

Install Preact dependencies

npm i babel-core babel-loader babel-plugin-transform-react-jsx babel-preset-es2015 babel-preset-stage-0 browser-sync concurrently gulp gulp-sass preact webpack

Add npm scripts

npm start

We’re using concurrently module to run both:

  1. Webpack: which uses Babel to simply transforms your ES6 code into ES5, which is the current standard that browsers can process.
  2. Gulp: which copies html files to “dist” folder, convert SCSS to CSS, hosts your app on a local server, and refreshes when changes happen.

npm run build

This command runs webpack, but with -p argument, which means “production” to minify and uglify JS code.

So ultimately, your “package.json” file should look like this


This code just tells webpack from where to start “entry”, where to output the result “output”, and what modules to use.


Four tasks:

  1. copy:html: simply copies html files from “src” folders to “dist” folder.
  2. sass: converts scss files in “src” folder to css files in “dist” folder.
  3. browser-sync: which hosts your app on a local server and refreshes when changes happen.
  4. watch: watch all files and call a different task for each type of files accordingly.


Simple html file that includes “style.css” and “bundle.js” files.



Adding nice color to the SVG chart, and add transition, so it animates.



Full code

App state

Shuffle data

Chart component

SVG that has as many rectangles as the amount of items data array has.

To make lines represent the data we have, we made the height={item}, and because the rectangles grow downwards not upwards we had to do this trick y={120 — item}120” is the height of the svg. So, it starts from the value of the item to the bottom.

To spread them over the svg we moved each line by its width “40” + 3 pixels for spacing and multiplied them by the index, as they all start at the same point.

Let’s run it

npm start

Github link


Next time you need a simple chart for your app try code it yourself instead of loading an 80KB library. Consider using a light-weight (3KB gizpped) library like Preact for your projects.