Access Child Canvas Element From Parent Component

- 1 answer

I am building a app where one can sign with pointer.

I have installed react-canvas-signature.

Now I need to get signature from the canvas and show it as a popup, and in their Readme files is said that there is a function toDataURL()

toDataURL(mimetype, encoderOptions): base64string, returns the signature image as a data URL

It says they are accessed through API

All API methods require a ref to the SignatureCanvas in order to use and are instance methods of the ref. <SignatureCanvas ref={(ref) => { this.sigCanvas = ref }} />

However, I am unable to access this function or any function described there. I have tried to use useRef(), createRef() but still nothing. Maybe I am just not doing it right.

Please find below parent component without unnecessary lines:

import React, { createRef } from 'react';
import ReactCanvas from 'react-signature-canvas';

interface IProps {}

interface IState {}

export default class App extends React.Component<IProps, IState> {
  constructor(props: IProps) {
    this.state = {};
  render() {
    return (
      <div className="content-area">
        <ReactCanvas penColor='black' canvasProps={{width: 353, height: 120}} />

I have tried to create ref like so private myRef = createRef<ReactCanvas>() and then to use it

const canvasRef = this.myRef.current
    if (canvasRef) {
      canvasRef.props.toDataURL('image/png', 1);

and it says

Property 'toDataURL' does not exist on type 'Readonly & Readonly<{ children?: ReactNode; }>'.

ref is in child element like this <ReactCanvas penColor='black' canvasProps={{width: 353, height: 120}} ref={this.myRef} />

Can you please show how should I do it, or even a direction/suggestion will be very appreciated.



I have found a way.

Firstly I needed to create empty object sigCanvas: any = {}, next I use it to create ref in the ReactCanvas component <ReactCanvas minWidth={1} maxWidth={2} canvasProps={{width: 353, height: 120}} ref={(ref) => { this.sigPad = ref }} /> and then I could use it in the functions like so

getCanvasImage = () => {
    this.setState({toDataUrl: this.sigPad.getTrimmedCanvas()
      .toDataURL('image/png', 1)})