Avatar ·

How to correctly use useRef and createRef in React with TypeScript: typing refs

Hello everyone! I'm new to React and TypeScript, and I have a problem with using refs. I'm trying to access a DOM element (for example, an input field) via useRef, but TypeScript keeps throwing type errors. Here's my code: ```typescript import React, { useRef, useEffect } from 'react'; const MyComponent: React.FC = () => { const inputRef = useRef(null); // Error: Argument of type 'null' is not assignable to parameter of type 'HTMLInputElement' useEffect(() => { inputRef.current?.focus(); // Error: Property 'focus' does not exist on type 'never' }, []); return ; }; ``` I've tried different options, but TypeScript complains either about the initialization of `useRef(null)` or about trying to call `focus()`. I tried using