Setting focus on an element can be done in three ways in React JS.
- Using useRef hook
- Using autoFocus property
- 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
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
The advantage using the useRef hook is it is easy to customize when to focus on the element. The focusing code
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
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
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