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:
useRefwhich stores refference to aninputelement,useEffectin which.focus()method is called to get focus on theinputelement whenAppcomponent is ready.
Runnable example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const App = () => {
const inputRef = React.useRef();
React.useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
return (
<div>
<label>Search: </label>
<input ref={inputRef} />
</div>
);
}
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );