- Instant help with your JavaScript coding problems

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.

Share "How to focus HTML element with React?"