Introduction
Let's take a look at how to access the DOM elements directly.
We'll cover the following
What are Refs?
Refs allow us to directly access DOM elements that were created during the render process. ven if this is unnecessary in most cases, it can be useful in a few situations where it is unavoidable. Examples are calculating the position or size of an element to display a tooltip based on the element or focusing on a form field using .focus()
once the component has loaded.
React has evolved over the years, and so have the methods dealing with Refs. But they all have one thing in common. Refs are always defined by the ref
prop of a DOM element in JSX, or to be more precise, createElement()
.
When to use Refs?
A word of warning before we proceed. Even though Refs exist, they should be used sparingly and only if the declarative way of re-rendering components with updated state and props does not help us. Manipulation of attributes or attribute values, or adding or removing classes, event listeners, or changing properties like aria-hidden
should always occur declaratively using props, state, JSX, and re-rendering.
However, there are a few cases in which using Refs is acceptable or even necessary. These are:
- Setting focus on an input element (
input.focus()
) or calling methods such as.play()
or.pause()
on video or audio elements. - Invoking imperative animations.
- Reading properties of elements currently in the DOM (for example
.getBoundingClientRect()
).
Get hands-on with 1200+ tech skills courses.