I have a problem with useRef in TypeScript.
I want to type it but I get an error, like this:
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.
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) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With