EN
React - set focus on input after rendering
3 points
In this article we would like to show you how in React set focus on input
element immediately after component rendering.
In below example we use two React hooks:
useRef
which stores refference to aninput
element,useEffect
in which.focus()
method is called to get focus on theinput
element whenApp
component is ready.
Runnable example:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => {
6
const inputRef = React.useRef();
7
React.useEffect(() => {
8
if (inputRef.current) {
9
inputRef.current.focus();
10
}
11
}, []);
12
return (
13
<div>
14
<label>Search: </label>
15
<input ref={inputRef} />
16
</div>
17
);
18
}
19
20
const root = document.querySelector('#root');
21
ReactDOM.render(<App />, root );