I am unable to autofocus the input tag rendered in this component. What am I missing here?
class TaskBox extends Component {
constructor() {
super();
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:
componentDidMount(){
this.focus();
}
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.
Reference: https://facebook.github.io/react/docs/react-component.html
Set an ID to the input and then use .setAttribute('autoFocus', true)
to the element when you want it focused