javascriptreactjsdomwkhtmltoimage

Problems using html-to-image in a React application


I am trying to use html-to-image to create a downloadable image of a specific html card. In its documentation it specifies to use

var node = document.getElementById('my-node');
htmlToImage.toPng(node)...

But this works on real DOM and not in react. I tried using refs but its unfruitful. The card and the download button is in different branches in Component Hierarchy.


Solution

  • Have you tried using the new React Ref

        class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        this.myRef = React.createRef();
      }
      render() {
        return <div ref={this.myRef} />;
      }
    }
    

    In order to access the element, use:

    const node = this.myRef.current;