rn-perfect-sketch-canvas
rn-perfect-sketch-canvas copied to clipboard
'useRef' for Javascript
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.
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.
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!
This is aidyun's other account btw