How to autofocus an input element in React using useRef() hook

#react #reacthooks

Last updated on Jan 3, 2021 by Suraj Sharma



In this tutorial, you're going learn how you can auto focus an input element in React using,


  1. the useRef() in the function component and,

  1. the createRef in the class 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. Auto-focus in function component


We cannot create an element Ref in the React function 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.


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


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 the focus() method on re-render.


const emailInputRef = React.useRef(null);

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

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


2. Auto-focus in class component


First, we are going to refactor the above Form component to a class component.


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;


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


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.



Related Solutions



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