AutoFocus an input element in react JS

There is a attribute available for auto focusing autoFocus, we can use that for auto focusing of input element instead of using ref.

Using autoFocus with input element:

<input autoFocus />

We can also use ref, but with ref we need to call focus method at correct place, you are calling that in componentWillUpdate lifecycle method, that method will not triggered during initial rendering, Instead of that use componentDidMount lifecycle method:


shouldComponentUpdate: is always called before the render method and enables to define if a re-rendering is needed or can be skipped. Obviously this method is never called on initial rendering. It will get called only when some state change happen in the component.

componentWillUpdate gets called as soon as the the shouldComponentUpdate returned true.

componentDidMount: As soon as the render method has been executed the componentDidMount function is called. The DOM can be accessed in this method, enabling to define DOM manipulations or data fetching operations. Any DOM interactions should always happen in this.


Leave a Comment