hey guys i try to make handlesave and handle clik like below but i am new to typescript and get error for cropRef.current
error:
‘cropRef.current’ is possibly ‘null’.
here the code handle save
const handleSave = async () => {
if (cropRef) {
const dataUrl = cropRef.current.getImage().toDataURL();
const result = await fetch(dataUrl);
const blob = await result.blob();
setPreview(URL.createObjectURL(blob));
setModalOpen(false);
}
};
error:
‘inputRef.current’ is possibly ‘null’.
code handle click
const handleInputClick = (e) => {
e.preventDefault();
inputRef.current.click();
};
do you guys know how to solve this kind of error ? please tell me in detail because i am still learning about typescript its new to me
2
Answers
cropRef
andinputRef
is not defined anywhere in your code. I am assumingpossibly
indicates that the compiler cant tell what the attachment is because the value has not been defined (typescript specific). In JavaScript, I think the error would becan not read value of undefined
.When you use the
useRef
hook in React, for example to get a handle on an HTML element that you can render, it’s common practice to give the ref a default value ofnull
.This default value will be the ref’s value until it’s set to something else. For example, if it’s being set to an HTML element via a
ref
prop then it will remainnull
during the component’s initial render pass, when it hasn’t yet been inserted into the DOM, (and it would also benull
if the ref is on an element that isn’t always rendered).TypeScript Playground
If you use
createRef
and you don’t pass a default value,null
will be used by default as well. It’s not clear from your question exactly how your ref is created.The easiest way to deal with this is just to check that
cropRef.current !== null
, so you’ll never try to access properties on it while it isnull
. Depending on what possible values might be stored in your ref, sometimes just a check for truthiness might be enough, i.e.if (cropRef.current) { // ...
Sometimes, you may find it convenient to just use optional chaining to access a property via
?.
only if your ref’s current value is notnull
orundefined
, e.g.cropRef.current?.getImage().toDataURL()