Home > References > Web Development > Reactjs references

Set focus on any element in react js

Last updated : July 14, 2022

Setting focus on an element can be done in three ways in React JS.

  1. Using useRef hook
  2. Using autoFocus property
  3. Using inline element ref

Focus using useRef hook

Using useRef is the most flexible way to focus on an element. First we create a useRef object and assign it to the html element we want to focus. Then we can use the ref.current?.focus() to focus on the element. The example shows how to focus on an element on page load.

export const App = () => {
const usa = useRef<HTMLInputElement>(null);

useEffect(() => {
  usa.current?.focus()
},[])

return(
<div>
 <h2>React Focus element</h2>
<table>
  <tr>
    <th>Country</th>
    <th>Code</th>
  </tr>
  <tr>
    <td>UNITED STATES</td>
    <td><input type="text" value="" ref={usa}/></td>
  </tr>
  <tr>
    <td>CANADA</td>
    <td><input type="text" value=""/></td>
  </tr>
</table>
</div>
   )
}
export default App
React focus element with useRef
Figure 1: React focus element with useRef:

The advantage using the useRef hook is it is easy to customize when to focus on the element. The focusing code ref.current?.focus() can be easily plugged into other logic to decide when to focus.

Focus using autoFocus property

The autoFocus is an HTML5 attribute. Therefore it has browser compatibility issues. It is also less flexible. The autoFocus is meant to be used on the initial page load.

export const App = () => {
return(
<h2>React Focus element</h2> <table> <tr> <th>Country</th> <th>Code</th> </tr> <tr> <td>UNITED STATES</td> <td><input type="text" value="" ref={usa}/></td> </tr> <tr> <td>CANADA</td> <td><input type="text" value="" autoFocus/></td> </tr> </table> </div> ) } export default App
React focus with autoFocus
Figure 2 : React focus with autoFocus

Focus using inline element ref

This method provides the ref object inline. The advantage is we can control when to focus. Just like the useRef method, but without explicitly defining a ref object. The simple usage is <input type="text" value="" ref={input => input && input.focus()}/>. The below example shows the logical usage of inline element ref.

import { useState } from "react";
export const App = () => {
const [state,] = useState(true)
return(
<div>
 <h2>React Focus element</h2>
<table>
  <tr>
    <th>Country</th>
    <th>Code</th>
  </tr>
  <tr>
    <td>UNITED STATES</td>
    <td><input type="text" value=""/></td>
  </tr>
  <tr>
    <td>CANADA</td>
    <td><input type="text" value="" ref={input => {state && (input && input.focus())}}/></td>
  </tr>
</table>
      </div>
     )
}
export default App
React focus with inline ref
Figure 3 : React focus with inline ref
L Raney
By: L Raney
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Comments are disabled

No Comments