plotly / react-plotly.js

A plotly.js React component from Plotly 📈
MIT License
1.01k stars 135 forks source link

Need to extract `.default` before using `createPlotlyComponent` #335

Closed EarlMilktea closed 7 months ago

EarlMilktea commented 8 months ago

Thank you for making this awesome library!

Let me report a bug in the documentation and .d.ts file for TypeScript.

Summary

I found a bug in documentation and associated type declaration.

Similar behavior is also reported here.

Package Versions

I'm using esbuild to bundle and runing it on Brave 120.1.61.114 (Arch Linux).

Description

The document and .d.ts says that createPlotlyComponent can be used as follows:

import Plotly, { type Layout, type PlotData } from "plotly.js-dist-min";
import { createRoot } from "react-dom/client";
import createPlotlyComponent from "react-plotly.js/factory";

// function createPlotlyComponent(plotly: object): React.ComponentType<PlotParams>;
const Plot = createPlotlyComponent(Plotly);

export function MyElement() {
  const trace: Partial<PlotData> = {
    x: [1, 2, 3],
    y: [1, 2, 3],
    type: "scatter",
  };
  const layout: Partial<Layout> = {};
  return <Plot data={[trace]} layout={layout} />;
}

const element = document.getElementById("target");

if (element === null) {
  throw new Error("Element not found");
}

// Runtime exception
createRoot(element).render(<MyElement />);

But it results in Uncaught TypeError: (0 , import_factory.default) is not a function.

Actually, I needed to extract .default memeber before calling it.

import Plotly, { type Layout, type PlotData } from "plotly.js-dist-min";
import { type ComponentType } from "react";
import { createRoot } from "react-dom/client";
import { type PlotParams } from "react-plotly.js";
import factory from "react-plotly.js/factory";

// Cast to make tsc happy
// extract factory.default and name it createPlotlyComponent
const createPlotlyComponent = (
  factory as unknown as {
    default: (plotly: object) => ComponentType<PlotParams>;
  }
).default;

const Plot = createPlotlyComponent(Plotly);

export function MyElement() {
  const trace: Partial<PlotData> = {
    x: [1, 2, 3],
    y: [1, 2, 3],
    type: "scatter",
  };
  const layout: Partial<Layout> = {};
  return <Plot data={[trace]} layout={layout} />;
}

const element = document.getElementById("target");

if (element === null) {
  throw new Error("Element not found");
}

// OK
createRoot(element).render(<MyElement />);

I'm now planning to submit a PR.

EarlMilktea commented 7 months ago

I noticed it works fine with this tsconfig.json. Closing.