reactjstypescriptsignaturepaduse-ref

How to use SignaturePad with React TypeScript


I'm trying to implement the SignaturePad in my react project and I can draw the signature, but I can't access the properties in order to clear it or save it. I get the error below on the ref={signCanvas} and also the current.clear() and signCanvas.current.clear() and signCanvas.getTrimmedCanvas().toDataURL("image/png")

No overload matches this call.

  Overload 1 of 2, '(props: Readonly<ReactSignatureCanvasProps>): ReactSignatureCanvas', gave the following error.
    Type 'MutableRefObject<{}>' is not assignable to type 'string | ((instance: ReactSignatureCanvas | null) => void) | RefObject<ReactSignatureCanvas> | null | undefined'.
      Type 'MutableRefObject<{}>' is not assignable to type 'RefObject<ReactSignatureCanvas>'.
        Types of property 'current' are incompatible.
          Type '{}' is missing the following properties from type 'ReactSignatureCanvas': on, off, clear, isEmpty, and 14 more.
  Overload 2 of 2, '(props: ReactSignatureCanvasProps, context?: any): ReactSignatureCanvas', gave the following error.
    Type 'MutableRefObject<{}>' is not assignable to type 'string | ((instance: ReactSignatureCanvas | null) => void) | RefObject<ReactSignatureCanvas> | null | undefined'.
      Type 'MutableRefObject<{}>' is not assignable to type 'RefObject<ReactSignatureCanvas>'.ts(2769)
index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<ReactSignatureCanvas> & Readonly<ReactSignatureCanvasProps> & Readonly<...>'
index.d.ts(143, 9): The expected type comes from property 'ref' which is declared here on type 'IntrinsicAttributes & IntrinsicClassAttributes<ReactSignatureCanvas> & Readonly<ReactSignatureCanvasProps> & Readonly<...>'*

This is what I have implemented so far, Any help would be greatly appreaciated.

const signCanvas = useRef({});

const clear = () => signCanvas.current.clear();
const save = () => console.log(signCanvas.getTrimmedCanvas().toDataURL("image/png"));

<SignaturePad
 ref={signCanvas}
 canvasProps={{ className: "signature__canvas" }}
/>

<Button color='grey' content='Clear' onClick={clear} />
<Button color='grey' content='Save' onClick={save} />

Solution

  • I managed to fix this. If anyone has the same issue, just needed to add the below for the React.MutableRefObject

    const signCanvas = React.useRef() as React.MutableRefObject<any>;
    

    and the follow is working fine now.

     const clear = () => signCanvas.current.clear();
    
     const save = () =>
     console.log(signCanvas.current.getTrimmedCanvas().toDataURL("image/png"));