Focusing HTML element with React
Question:
How to focus HTML element with React? Answer:
const MyComponent = () => {
const elementRef = useRef(null);
useEffect(() => {
elementRef.current.focus();
}, []);
return (
<div ref={elementRef}>
Test div
</div>
)
}
Description:
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.
If you pass a ref object to React with <div ref={myRef} />
, React will set its .current
property to the corresponding DOM node whenever that node changes.
Reference:
React useRef reference
Share "How to focus HTML element with React?"
Related snippets:
Tags:
react focusing HTML element, react focus, html element Technical term:
Focusing HTML element with React