Introduction
By setting the focus on an element, we gently guide a user to the next expected input field, giving them a better browsing experience with less guesswork.
In this article, we will learn how to set focus on an element after rendering our React application or a React component.
In traditional HTML, it was easy to set an element to focus using the autofocus
attribute within our <input>
tag, which is a boolean attribute and is by default set to false
. It instructs the browser to focus on that specific input field, and the user can begin entering values immediately:
<form>
<input type="text" autofocus> // Will focus
<input type="text"> // Won't focus
</form>
This is going to work in our React applications as well. Still, when we want to set focus on an element after rendering with more programmatic control - we can make use of the useEffect()
hook in functional components and the componentDidMount()
lifecycle method in class components.
How to Set Focus On Element After Rendering in Functional Components
Previously, before the introduction of React hooks, we could not handle operations like this with Functional components.
Since the introduction of hooks, we can know when our application/component has fully rendered so that we can perform specific actions using the useEffect()
hook. We also have access to the useRef()
hook, which we can use to reference a particular element directly.
Suppose we have a form with two fields, and we want one of the fields to be set on focus after the component renders:
const App = () => {
return (
<div className='container'>
<form>
<input type="text" placeholder='This has focus' />
<input type="text" placeholder='No focus when we render' />
</form>
</div>
)
}
export default App;
Let's get started by getting a reference to the input using the useRef()
React hook. To do this, we would first import useRef()
from React, create a ref
and set its value to null by default then and then attach the created ref
to our React element via the ref
attribute:
import { useRef } from 'react';
const App = () => {
const inputReference = useRef(null);
return (
<div className='container'>
<form>
<input type="text" ref={inputReference} placeholder='This has focus' />
<input type="text" placeholder='No focus when we render' />
</form>
</div>
)
}
export default App;
Note: Notice we only attached the created reference to one of the input elements, which is the one we want to set to focus.
Let's now proceed to use the useEffect()
hook to add focus to the element after rendering our application:
import { useRef, useEffect } from 'react'
const App = () => {
const inputReference = useRef(null);
useEffect(() => {
// ...
}, [])
return (
<div className='container'>
<form>
<input type="text" ref={inputReference} placeholder='This has focus' />
<input type="text" placeholder='No focus when we render' />
</form>
</div>
)
}
export default App;
In the code above, notice that we imported the useEffect()
hook and then made use of the hook with an empty dependency array ([]
) to make sure it only fires when the component initially mounts. Finally, to make the referenced element focus, we will access the ref via the current
attribute and then attach the focus()
method:
useEffect(() => {
inputReference.current.focus();
}, [])
At this point, when our application or component renders, the referenced element will automatically be focused:
import { useRef, useEffect } from 'react';
const App = () => {
const inputReference = useRef(null);
useEffect(() => {
inputReference.current.focus();
}, []);
return (
<div className='container'>
<form>
<input type="text" ref={inputReference} placeholder='This has focus' />
<input type="text" placeholder='No focus when we render' />
</form>
</div>
)
}
export default App;
How to Set Focus On Element After Rendering in Class Components
So far, we have seen how to set focus on an element with a functional component, but it's an entirely different syntax with class components as we no longer make use of hooks because they only work in functional components. In class components, we create our ref within the constructor()
method and make use of the componentDidMount()
method to set the referenced element to focus once our application renders:
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
import React, { Component } from 'react';
export class App extends Component {
constructor(props) {
super(props);
this.inputReference = React.createRef();
}
componentDidMount() {
this.inputReference.current.focus();
}
render() {
return (
<div className='container'>
<form>
<input type="text" ref={this.inputReference} placeholder='This has focus' />
<input type="text" placeholder='No focus when we render' />
</form>
</div>
)
}
}
export default App;
In the code above, we used the constructor()
method to create a reference, which we attached to the input element:
constructor(props) {
super(props);
this.inputReference = React.createRef();
}
We then used the componentDidMount()
lifecycle method, which is very similar to the useEffect()
hook, to ensure that the element is set on focus once our application/component renders:
componentDidMount() {
this.inputReference.current.focus();
}
Conclusion
In this article, we have learned how to set an element to focus using an input field once our application or component renders in both the Class and Functional components. Both methods are the same but have different syntax since they are two different types of components.