Autofocusing an Element on Page Load in React.js

Autofocus is particularly useful in forms or interactive pages where immediate user input is expected. Rather than making a user click to navigate to an input or tab their way there, you can autofocus so they can get to typing.

In this short article, we will look at how you can implement autofocusing of inputs in React:

Implementing Autofocus in React.js

This will be done using useRef and the useEffect hook. Here’s how:

1) Import Necessary Hooks

First, import useRef and useEffect from React:

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

2) Create a Ref

Create a ref for the element you want to focus:

const inputRef = useRef(null);

3) Apply the Ref to Your Element

Attach this ref to the desired input element in your JSX:

<input ref={inputRef} type="text" />

4) Use the useEffect Hook

Use the useEffect hook to set the focus when the component loads:

useEffect(() => {
  // Focus the input element
  inputRef.current.focus();
}, []);

Putting it all together

  • useRef creates a reference (inputRef) to the input element.
  • The input element is linked to this ref.
  • useEffect ensures that as soon as the component renders, the focus is set on the input.

Here’s what the complete component might look like:

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

function AutoFocusedInput() {
  const inputRef = useRef(null);

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

  return (
    <div>
      <label>
        Username:
        <input ref={inputRef} type="text" />
      </label>
    </div>
  );
}

export default AutoFocusedInput;

I hope this helps! ✌️

Reactjs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.