react-plotly.js icon indicating copy to clipboard operation
react-plotly.js copied to clipboard

Concept for plotly.js with Functional component, TypeScript

Open tony opened this issue 4 years ago • 1 comments
trafficstars

Hi, thank you very much for the project! (And plotly.js, and the docs, and the team for helping on these projects, and all other contributors as well! And anyone else note mentioned!)

For the react component, by 2020 standards, I don't consider the current state of this project to be a "lite" react wrapper. I wanted to provide this for inspiration purposes.

Gist: https://gist.github.com/tony/f0938e379aef3c49648a2b1b63e00807

Sandbox: https://codesandbox.io/s/react-plotlyjs-minimal-c6k7f

yarn add -D @types/plotly.js / npm install --save-dev @types/plotly.js yarn add plotly.js / npm install --save-dev plotly.js

import React from "react";
import Plotly from "plotly.js/dist/plotly";
export interface ChartProps {
  data?: Plotly.Data[];
  layout: Partial<Plotly.Layout>;
  frames?: Plotly.Frame[];
  config?: Partial<Plotly.Config>;

  // react-specific
  style?: React.CSSProperties;
}

export const Chart: React.FC<ChartProps> = ({
  style = {},
  data,
  ...props
}) => {
  const ref = React.useRef<HTMLDivElement>(null);
  React.useEffect(() => {
    Plotly.react(ref.current, { data, ...props });
  }, [props, data]);

  return <div ref={ref} style={style} />;
};

custom.d.ts

declare module "plotly.js/dist/plotly" {
  export { Plotly as default } from "plotly.js";
}

Notes

  • I removed useResponsiveHandler since there's config = {{ responsive: true }} as of https://github.com/plotly/plotly.js/pull/2974 / Sep 7, 2018 / v1.41.0 / https://github.com/plotly/plotly.js/commit/cfc720bd3c127ea0e206b4e3c2217b356ca92425

    If you want support for it, you do this:

    export const Chart: React.FC<ChartProps> = ({
      style = {},
      useResizeHandler = false,
      data,
      ...props
    }) => {
      const ref = React.useRef<HTMLDivElement>(null);
      React.useEffect(() => {
        Plotly.react(ref.current, { data, ...props });
      }, [props, data]);
    
      const resizeHandler = React.useCallback(
        () => Plotly.Plots.resize(ref.current),
        [ref]
      );
    
      React.useEffect(() => {
        if (useResizeHandler) {
          window.addEventListener("resize", resizeHandler);
          return () => window.removeEventListener("resize", resizeHandler);
        }
      }, [resizeHandler]);
    
      return <div ref={ref} style={style} />;
    };
    
  • Sandbox: https://codesandbox.io/s/react-plotlyjs-minimal-c6k7f

    There's an unrelated issue with plotly.js and document on codesandbox: https://github.com/plotly/plotly.js/issues/3518#issuecomment-753532505)

tony avatar Jan 02 '21 21:01 tony

This is brilliant!

Perfect for my use case and one less dependency!

damienallen avatar Sep 22 '23 13:09 damienallen