Languages
[Edit]
EN

React - set focus on input after rendering

3 points
Created by:
Krzysiek
651

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';
// 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 );
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

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.

❤️💻 🙂

Join