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

Finding the Right HTMLElement Type

Discover how to determine which specific HTML element type to use for different DOM nodes.

Finding the Right HTMLElement Type

What you'll learn: How to discover and use the correct specific HTML element type when typing refs in React components.

The Detective Work

You know you need useRef<HTMLElement> for DOM nodes, but which element? TypeScript offers dozens of specific types: HTMLInputElement, HTMLDivElement, HTMLButtonElement, and more. Using the wrong one means you lose access to element-specific properties like input.value or button.disabled.

Discovery Strategies

Hover in Your Editor

The fastest method: create an untyped ref, assign it to a JSX element, then hover over that element in your editor. TypeScript will show you exactly what type React expects:

const ref = useRef(null);
// Hover over "input" below to see: React.DetailedHTMLProps<...HTMLInputElement...>
<input ref={ref} />

The key part is HTMLInputElement.

Read the Error Message

If you use useRef<HTMLElement> on a specific element, TypeScript often tells you what it wanted instead:

const buttonRef = useRef<HTMLElement>(null);
// Error might say: Type 'HTMLButtonElement' is not assignable...

There's your answer: use HTMLButtonElement.

Common Patterns

  • Form controls: HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement
  • Interactive: HTMLButtonElement, HTMLAnchorElement
  • Containers: HTMLDivElement, HTMLSpanElement
  • Media: HTMLImageElement, HTMLVideoElement
  • Canvas: HTMLCanvasElement

Generic HTMLElement as Fallback

If you only need basic properties (like focus() or getBoundingClientRect()), HTMLElement works for any HTML element. But you lose element-specific properties.

Key Takeaway: Use editor hover tooltips and TypeScript errors as your guide to finding the precise HTML element type—specificity gives you better autocomplete and catches more bugs.