Question:
How to solve error possibly 'null' for Typescript

Problem

Hey guys I try to make handlesave and handle clik like below but I am new to typescript and get an 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 it is new to me


Solution

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 of null.


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 remain null during the component's initial render pass, when it hasn't yet been inserted into the DOM, (and it would also be null if the ref is on an element that isn't always rendered).


import React, { useEffect, useRef } from 'react';


function MyComponent() {

    const rootRef = useRef<HTMLDivElement>(null);


    console.log(rootRef.current); // <- `null` the first time, then a `HTMLDivElement`


    useEffect(() => {

        console.log(rootRef.current); // <- Always a `HTMLDivElement`, because `useEffect` runs after rendering

    }, [])


    return <div ref={rootRef}></div>;

}


>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 is null. 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 property via ?. only if your ref's current value is not null or undefined, e.g. cropRef.current?.getImage().toDataURL()


Suggested blogs:

>Why Typescript does not allow a union type in an array?

>Narrow SomeType vs SomeType[]

>Create a function that convert a dynamic Json to a formula in Typescript

>How to destroy a custom object within the use Effect hook in TypeScript?

>How to type the values of an object into a spreadsheet in TypeScript?

>Type key of record in a self-referential manner in TypeScript?

>How to get the last cell with data for a given column in TypeScript?

>Ignore requests by interceptors based on request content in TypeScript?

>Create data with Typescript Sequelize model without passing in an id?

>How to delete duplicate names from Array in Typescript?


Nisha Patel

Nisha Patel

Submit
0 Answers