hugocxl / react-to-image

📸 Hooks for converting your React components to images
MIT License
112 stars 4 forks source link

Error inlining css files when triggering the conversion on mounting #103

Closed seebham closed 3 weeks ago

seebham commented 3 months ago

Description

I want to trigger the conversion on mounting of the component. I have implemented it like this:

import { useToPng } from '@hugocxl/react-to-image';
import React, { useEffect } from 'react';
import { Slide } from '../preview/slide';

type SlideToPNGProps = {
  index: number;
  heading: string;
  body: string;
  onSuccess: (data: string, index: number) => void;
  onError?: (error: string, index: number) => void;
};

export const SlideToPNG: React.FC<SlideToPNGProps> = ({
  index,
  heading,
  body,
  onSuccess,
  onError,
}) => {
  const [_, convert, setSlideRef] = useToPng<HTMLDivElement>({
    quality: 1,
    height: 1350,
    width: 1080,
    canvasHeight: 1350,
    canvasWidth: 1080,
    onSuccess: (data) => {
      console.info(`Conversion successful for slide ${index}`, data);
      onSuccess(data, index);
    },
    onError: (error) => {
      console.error(`Error converting slide ${index}:`, error);
      if (onError) {
        onError(error, index);
      }
    },
  });

  useEffect(() => {
    const timeoutId = setTimeout(() => {
      convert();
    }, 10);

    return () => {
      clearTimeout(timeoutId);
    };
  }, [convert]);

  return (
    <div className="fixed -top-[100vh] -left-[100vw] w-[1080px] h-[1350px]">
      <Slide
        index={index}
        setSlideRef={setSlideRef}
        heading={heading}
        body={body}
        size="l"
      />
    </div>
  );
};

However, the converted images are blank and while conversion I'm getting the following error: Error inlining remote css file DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules Also, the useEffect keeps on running infinitely.

Any idea why? Also, I'm suspecting it's the issue with the closure of the convert().

Link to Reproduction

https://stackblitz.com/edit/react-tbku9t?file=src%2FApp.js

Steps to reproduce

No response

Version

0.0.9

Browser

No response

Operating System

Additional Information

No response

hugocxl commented 3 months ago

hi @seebham, I saw that your reproduction example is working (do no need to pass the convert fn as dependency to the useEffect. Is it ok then?