How to Focus an Input Field in React After First Render?

Auto-Focusing on Mount

The autoFocus property (notice the camel case) in React tries to fix cross-browser inconsistencies with the autofocus HTML attribute. To use the autoFocus property, you could simply set it to boolean true or false (which would set an input field to focus on mount accordingly) like so:

<input type="text" autoFocus />

Dynamically Focusing

You could use the HTMLElement.focus() method to set focus to an element on first render in the following way:

import React, { useRef, useEffect } from 'react';

const Foo = () => {
    const ref = useRef(null);

    useEffect(() => {
        ref?.current?.focus?.();
    }, [ref]);

    return <input type="text" ref={ref} />;
};

As you can see from the code above, in order to set focus on the element, you need to get a reference to it. You could also inline the code to set focus on the element, in the ref property, like so:

import React from 'react';

const Foo = () => (
    <input
        type="text"
        ref={(element) => element?.focus?.()}
    />;
);

If you don't have support for optional chaining, you could instead use short-circuit evaluation like so: element && element.focus(). Alternatively, you may also use an if statement.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.