Home > OS >  Using div React useRef hook, typescript?
Using div React useRef hook, typescript?

Time:12-02

I'm using a qrcode.react library and creating useRef hook

const qrRef = React.useRef();

and then using it in

const downloadQRCode = (evt: React.FormEvent) =>{
        evt.preventDefault();

        // @ts-ignore
        let canvas = qrRef.current.querySelector("canvas");
        let image = canvas.toDataURL("image/png");
        let anchor = document.createElement("a");
        anchor.href = image;
        anchor.download="qr-code.png";
        document.body.appendChild(anchor);
        anchor.click();
        document.body.removeChild(anchor);
        
        setUrl("");
    };
<div className="qr-container">
    <form onSubmit={downloadQRCode} className="qr-container_form">
       <input
         type="text"
         value={url}
         onChange={(e) => setUrl(e.target.value)}
         placeholder="https://example.com"
       />
       <button type="submit">Download QR Code</button>
    </form>
    <div className="qr-container_qr-code" ref={qrRef}>{qrCode}</div>
</div>

and I'm getting this error

Type 'MutableRefObject<undefined>' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.
  Type 'MutableRefObject<undefined>' is not assignable to type 'RefObject<HTMLDivElement>'.
    Types of property 'current' are incompatible.
      Type 'undefined' is not assignable to type 'HTMLDivElement | null'.ts(2322)
index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'

Basically all it has to does is to download QR code which has been generated.

CodePudding user response:

try initialising it with:

const qrRef = React.useRef<HTMLDivElement>(null);
  • Related