React Refs

React useRef Hook

Ref

Refs provide a way to access DOM nodes or React elements created in the render method.

usecases

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

Example to focus a text field

1
2
3
4
5
6
7
8
9
10
11
12
13
function TextFieldFocus() {
const inputRef = useRef();

const clickHandler = () => {
inputRef.current.focus();
}
return (
<>
<input ref={inputRef} type="text" />
<button onClick={() => clickHandler()}>Focus the input</button>
</>
)
}

Reference