Skip to content

Concept for plotly.js with Functional component, TypeScript #226

Open
@tony

Description

@tony

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 add support for responsive charts plotly.js#2974 / Sep 7, 2018 / v1.41.0 / plotly/plotly.js@cfc720b

    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: Native ES6 modules vs. the bundle plotly.js#3518 (comment))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions