Search code examples
javascriptreactjschart.jsreact-chartjsexport-to-image

React export component that is not diplayed to PNG


I'm trying to export a chart to an image and I want the chart image to have a custom legend that is not being displayed on screen.

How can I do that?

For now I have tried to export using react-component-export-image but if the component is not displayed the ref is null and It cannot be exported. See component export implementation src-code.

Example of my current code: codesandbox


Solution

  • The only way you can achieve that by manipulating the canvas before render. You can do that by setting the onclone option in html2CanvasOptions.

    import { Line } from "react-chartjs-2";
    import { exportComponentAsPNG } from "react-component-export-image";
    import React, { useRef } from "react";
    import { data } from "./data";
    
    const Chart = React.forwardRef((props, ref) => {
      return (
        <div ref={ref} style={{ maxWidth: "800px" }}>
          <Line data={data} height={80} />
          <div id="legend" style={{ textAlign: "center", visibility: "hidden" }}>
            Legend
          </div> {/* Visibility set to hidden using css */}
        </div>
      );
    });
    
    const App = () => {
      const componentRef = useRef();
    
      return (
        <React.Fragment>
          <Chart ref={componentRef} />
          <button
            style={{ margin: "30px" }}
            onClick={() => exportComponentAsPNG(componentRef, {
                html2CanvasOptions: {
                  onclone: (clonedDoc) => {
                    clonedDoc.getElementById("legend").style.visibility = "visible";
                    // Visibility set to visible using `onclone` method
                  },
                },
              })
            }
          >
            Export As PNG
          </button>
        </React.Fragment>
      );
    };
    
    export default App;
    

    https://codesandbox.io/s/export-chart-821kc?file=/src/App.js

    This will do the job. Let me know if you need further support.