rn-perfect-sketch-canvas icon indicating copy to clipboard operation
rn-perfect-sketch-canvas copied to clipboard

'useRef' for Javascript

Open aidyun opened this issue 2 years ago • 3 comments

I noticed that your example is in TypeScript. When I try copying the sample code into my JavaScript code, I get an error, saying:

Error: Function components cannot have string refs. We recommend using useRef() instead.

When I remove the useRef, there are no errors, but then I can't reset the canvas.

aidyun avatar Oct 15 '22 18:10 aidyun

As a quick fix, I removed <SketchCanvasRef> from useRef, which is just a type declaration (mandatory to use type declaration in TypeScript but not supported in JavaScript). The reset method (and other methods) still won't work, so to fix this, I used a callback function in the onPress Button, and then directly called the reset function.

Example: onPress={() => canvasRef.current?.reset()}

My guess at why this works is that SketchCanvas is a ForwardRefExoticComponent which contains the SketchCanvas props AND the RefAttributes of SketchCanvasRef. Coding in JavaScript, this means we can directly access those methods (reset, undo, etc.), without needing to declare their types handed to us with SketchCanvasRef. We just need to call these methods (functions) directly, but within a callback function as to not infinitely call them.

GabrielMurry avatar Apr 27 '23 05:04 GabrielMurry

Wow thanks for the response but I'm not using this library anymore its been nearly a year lol. Hopefully it helps someone else out!

sickopickle avatar Apr 27 '23 06:04 sickopickle

This is aidyun's other account btw

sickopickle avatar Apr 27 '23 06:04 sickopickle