Home

Awesome

react-use-d3

npm check demo

A small React hook to use D3 in declarative way, for data visualization & flexible animation.

NOTE: I recommend to use my new library https://github.com/inokawa/react-animatable

This is under development and APIs are not fixed

Why?

D3 is an excellent library to do data-driven visualization. React is a nice library to create user interfaces in data-driven way. So why not use them together?

Well, integrating D3 into React was tried by many. Someone uses a part of D3's possibilities in React but it looks that no one succeeded to port all of them. I think it's because of mismatches between D3 and React.

I'm trying to give a nice intermediate with this lib. Almost all syntaxes of D3 would work. The elements created with D3 are transformed into React Elements and handled by React's reconciliation. Attribute updates are applied directly through ref for smooth animation.

The core of this lib is based on react-faux-dom, but highly customized to fit to the lifecycle of React and handle D3's transition correctly. Also rewritten in TypeScript and fixed to support newest D3.

I'm trying to support D3's usecases as much as possible. If you notice some problems, I would appreciate if you could report it in a issue.

Demo

https://inokawa.github.io/react-use-d3/

Install

npm install react-use-d3

Requirements

Usage

import * as d3 from "d3";
import { useD3 } from "react-use-d3";

export const Component = ({ width, height, data }) => {
  const svg = useD3(
    (create) => {
      // create('foo') inits virtual element which accepts D3's mutations
      const svg = d3
        .select(create("svg"))
        .attr("width", width)
        .attr("height", height);
      svg
        .append("text")
        .attr("x", width / 2)
        .attr("y", height / 2)
        .attr("fill", "black")
        .text(data);
      return svg;
    },
    // deps of useD3 hook
    // useD3 hook runs if some of deps are updated like useMemo / useEffect
    [width, height, data]
  );
  // el.toReact() transforms virtual element into React element
  return <div>{svg.node().toReact()}</div>;
};

Limitations

TODO

TODOs

Inspirations