Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'MutableRefObject<HTMLInputElement | undefined>' is not assignable to type 'string | ((instance: HTMLInputElement | null) => void)

I have a problem with useRef in TypeScript.
I want to type it but I get an error, like this:
enter image description here My Container component is:

    const HeaderContainer: React.FC = () => {
    const addressElement = useRef<HTMLInputElement | undefined>();
    
        const handleCopy = useCallback(() => {
            if (addressElement.current !== undefined) {
                addressElement.current.select();
                document.execCommand("copy");
            }
        }, [addressElement]);
    return <HeaderUI
        addressElement={addressElement}
        handleCopy={handleCopy} />
}

And UI component is:

interface IProps {
    handleCopy: (event: React.MouseEvent) => void,
    addressElement: React.MutableRefObject<HTMLInputElement | undefined>,
}
const HeaderUI: React.FC<IProps> = ({
                                        handleCopy, addressElement
                                    }) => {
return <div className={classes.Header}>
        <div className={classes["Header-Section"]}>
            <span className={classes["Section-Title"]}>Персональный адрес кошелька:</span>
            {address && <input
              type="text"
              className={classes["Section-Value"]}
              ref={addressElement}
              value={address}
              readOnly/>}
        </div>
        <CopyLinkButtonContainer onClick={handleCopy}/>
    </div>;
}

Can you help please to fix this problem?

Thanks.

like image 453
Tigran Avatar asked Nov 27 '20 14:11

Tigran


1 Answers

The last line of the error is your solution: Your useRef expects the type

HTMLInputElement | null

but you're setting the type

HTMLInputElement | undefined


Just change your types to null instead of undefined:

const addressElement = useRef<HTMLInputElement | null>();

{... addressElement: React.MutableRefObject<HTMLInputElement | null>, ...}

and change your check to:

if (addressElement.current !== null) {

like image 181
Bennett Dams Avatar answered Sep 18 '22 16:09

Bennett Dams