I am unable to autofocus the input tag rendered in this component. What am I missing here?
class TaskBox extends Component { constructor() { super(); this.focus = this.focus.bind(this); } focus() { this.textInput.focus(); } componentWillUpdate(){ this.focus(); } render() { let props = this.props; return ( <div style={{display: props.visible ? 'block' : 'none'}}> <input ref={(input) => { this.textInput = input; }} onBlur={props.blurFN} /> <div> <div>Imp.</div> <div>Urg.</div> <div>Role</div> </div> <div> <button>Add goal</button> </div> </div> ) } }
Any help is appreciated.
While you're rendering a stateless component, you can just add the tag autoFocus to your input element and it will auto focus the element.
2.1 Use case: focusing an input To make it work you'll need to create a reference to the input, assign the reference to ref attribute of the tag, and after mounting call the special method element. focus() on the element. Try the demo. const inputRef = useRef() creates a reference to hold the input element.
To check if an element is focused in React:Set the ref prop on the element. After the element is rendered, check if the element is the active element in the document. If it is, the element is focused.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With