How to set focus on an input field after rendering?
Easily focus on an input field using useEffect()
and useRef()
in React:
This simple script leverages useRef
to specify a reference, and useEffect
to put the cursor in the input field when the component renders.
Navigating the autoFocus
prop
Adding a dollop of autoFocus
prop to static elements keeps things simple:
Just remember: autoFocus
does its thing when the component first mounts. Use sparingly to avoid messing with user navigation.
Going deeper into focus handling
Mastering focus with power techniques
Commanding class components with refs
For more control or for class components, createRef
comes to the rescue:
Make sure you give the ref to the right element.
Accessing DOM directly with ref callbacks
To apply focus in a single line, skip useRef
with an inline callback:
Pairing defaultValue
with refs
When working with controlled components, defaultValue
and refs go along like bread and butter. It allows value setting without triggering a re-render:
Taking dynamic focus and reusability to next level
Custom hooks for reusable focus
Custom hooks keep things DRY and your focus management sane:
Now, bring in your custom hook into components for reusable focus patterns.
Event-driven focus management
Sometimes, we want to focus only on a certain event:
Such an approach provides interactive control over focus setting.
The doom of findDOMNode()
, the rise of refs
Avoid findDOMNode()
like week-old sushi; it's deprecated. Instead, make the bees knees by accessing DOM nodes directly with refs.
Was this article helpful?