Languages
[Edit]
EN

React - set focus on input after rendering

3 points
Created by:
Dirask Community
1730

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 an input┬áelement,
  • useEffect┬áin which .focus() method is called to get focus on the input┬áelement when App component is ready.

Runnable example:

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
//import React from 'react';

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 );
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - friendly IT community for everyone.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join