Using html2canvas in a custom component in Sanity

11 replies
Last updated: Aug 19, 2021
if i want to use this script in my custom component where should i add it ???<script src=" "></script>
Aug 19, 2021, 6:59 AM
Like react i don't have index.html here in sanity so where to insert this piece of code???
Aug 19, 2021, 7:00 AM
Because it's all react inside Sanity, you'd do this the react way. Are you making a custom component or a plugin in Sanity? If so you should do
yarn add html2canvas
import html2canvas from 'html2canvas';
to start using it in your component. Then you'd use a ref ( ) in react to apply it to a component.
Aug 19, 2021, 7:20 AM
Can you guide me on how to use jquery inside custom component bcuz when i use it throws me with error document.getElementById is not a function ??
Aug 19, 2021, 7:24 AM
html2canvas(document.getElementById("myHtml"),                {
                    allowTaint: true,
                    useCORS: true
                }).then(function (canvas) {
                    var anchorTag = document.createElement("a");
           = "filename.jpg";
                    anchorTag.href = canvas.toDataURL();
           = '_blank';
Aug 19, 2021, 7:32 AM
Its always throwing document.getElementById is not a function
Aug 19, 2021, 7:32 AM
if you're using refs in react you don't use document.getElementById
Aug 19, 2021, 7:36 AM
Okay then how to use this?
Aug 19, 2021, 7:37 AM
I suppose something like this, but I haven't tested it or used html2canvas before

import { useRef, useEffect } from "react"

const myComponent = () => {
  const myRef = useRef();
  useEffect(() => {
    if (!myRef.current) return;
    html2canvas(myRef.current, {...});
  }, [myRef])

  return (<div ref={myRef}/>)
Aug 19, 2021, 7:42 AM
there is an example here that might do the same thing you are trying to do using html-to-image. Maybe you can find some inspiration there?
Aug 19, 2021, 7:46 AM
What does captureRef does in above does it capture the id of my div tag like getdocumentById?
Aug 19, 2021, 7:58 AM
I think captureRef would be the reference to your div element itself, not the id.
Aug 19, 2021, 8:07 AM

Sanity– build remarkable experiences at scale

The Sanity Composable Content Cloud is the headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?