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]);

    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 = () => (
        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.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.