9

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.

2 Answers 2

21

try initialising it with:

const qrRef = React.useRef<HTMLDivElement>(null);
Sign up to request clarification or add additional context in comments.

Comments

0

I think should be like this based on the error message you are getting

 const qrRef = useRef() as React.MutableRefObject<HTMLDivElement>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.