Course contentsShow
← React
Lesson 2362 of 2,39651. TypeScript with React BasicsFree lesson

useRef<HTMLElement> for DOM Refs

Learn how to type refs that point to DOM elements using the correct HTMLElement types.

useRef<HTMLElement> for DOM Refs

What you'll learn: How to properly type refs that point to actual DOM elements so TypeScript knows exactly what methods and properties are available.

The Core Idea

When you use useRef to grab a reference to a DOM element (like an input field or a button), TypeScript needs to know which kind of element you're referencing. Without the correct type, TypeScript can't help you catch errors when you try to call .focus() on an element that doesn't support it, or access properties that don't exist.

The pattern is simple: pass the specific HTML element type as a generic parameter to useRef, and initialize it with null:

const inputRef = useRef<HTMLInputElement>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
const divRef = useRef<HTMLDivElement>(null);

Why This Matters

Think of it like telling TypeScript, "I'm going to point at a text input box" versus "I'm going to point at any random thing." The more specific you are, the more TypeScript can verify you're using it correctly.

When you attach the ref to a JSX element, TypeScript verifies the types match:

function SearchBox() {
  const inputRef = useRef<HTMLInputElement>(null);

  const focusInput = () => {
    inputRef.current?.focus(); // TypeScript knows .focus() exists on HTMLInputElement
  };

  return <input ref={inputRef} type="text" />;
}

Notice inputRef.current might be null initially (before React attaches it), so you use optional chaining (?.) to safely access it.

Choosing the Right Type

Match the ref type to the actual element: HTMLInputElement for <input>, HTMLButtonElement for <button>, HTMLDivElement for <div>, and so on. TypeScript will then expose the correct methods and properties for that element type.

Key Takeaway: Type DOM refs with the specific HTMLElement subtype (like useRef<HTMLInputElement>(null)) so TypeScript can verify you're accessing the correct DOM properties and methods for that element.