How to autofocus an input element in React

#react #reacthooks

Last updated on Sep 21, 2020 by Suraj Sharma



In this tutorial, you will learn how you can auto focus an input element in React using a class component and a functional component.

Managing focus on input elements in React form are done using Refs.

Refs provide a way to access input elements and other React elements created in the render method.


I have divided the solutions in two sections:


1. Using a class component


Suppose we have a simple Form component and we want to autofocus the first input element in the form.


import React from 'react';

class Form extends React.Component {
  constructor(props) {
    super(props);
  }
  render () {
    return (
      <form>
        <input type="email" name="email" />
        <input type="password" name="password" />
        <button type="submit">Login</button>
      </form>
    )
  };
}

export default Form;


To reference the input element, we will need to create a Ref using React.createRef() and pass the ref to the input element via ref attribute.


constructor(props) {
  super(props);
  this.emailInputRef = React.createRef();
}
<form>
  <input type="email" name="email" ref={this.emailInputRef} />
  <input type="password" name="password" />
  <button type="submit">Login</button>
</form>


The input DOM node is accessible at the current property of the ref.


componentDidMount () {
  this.emailInput.current.focus();
}


Finally, to autofocus the input element, we have called the focus() method inside the componentDidMount() lifecycle method.



2. Using a functional component


We cannot create an element Ref in the React functional component using createRef() but React provides a useRef() hook, which returns a mutable ref object.

The current property of the ref is initialized to the passed argument in the useRef(initialValue) hook.

We are going to refactor the above Form component to a functional component.


import React from 'react';

const Form = () => {
  return (
    <form>
      <input type="email" name="email" />
      <input type="password" name="password" />
      <button type="submit">Login</button>
    </form>
  )
};
export default Form;


To autofocus the first input element in the form after render, we use useEffect() hook and call the focus() method inside the hook.

The dependency array should be an empty array to prevent multiple calls of focus() method on re-render.


const emailInputRef = React.useRef(null);

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

<input type="email" name="email" ref={this.emailInputRef} />


Related Articles




Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.