Using React's "useRef" hook with Typescript

Published

To use the useRef hook with Typescript, make sure to define a return type that matches your element type. In this example, the ref is to an HTMLInputElement.

function MyComponent() {
	const input = React.useRef<HTMLInputElement>(null);

	return (
		<form
			onSubmit={(e) => {
				e.preventDefault();
				alert("Value: " + input.current.value);
			}}
		>
			<input ref={input} />
		</form>
	);
}

Like this post?
Why don't you let me know on Twitter: @danawoodman