React - set focus on input after rendering

3 points
Created by:
Dirask Community

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) {
  }, []);
  return (
      <label>Search: </label>
      <input ref={inputRef} />

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );


React - set focus on input after rendering
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂