- Instant help with your JavaScript coding problems

Focusing HTML element with React

How to focus HTML element with React?
const MyComponent = () => {

    const elementRef = useRef(null);

    useEffect(() => {
    }, []);

    return (
        <div ref={elementRef}>
            Test div

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?"