AutoFocus input element in JS reaction

I cannot autofocus the input tag displayed 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.

+6
source share
2 answers

An attribute is available for auto focus autoFocus , we can use it to automatically focus the input element instead of ref .

Using autoFocus with an input element:

<input autoFocus />

We can also use ref , but with ref we need to call the focus method in the right place, you call it in the componentWillUpdate life cycle method, this method will not be triggered during the initial rendering, use the componentDidMount life cycle method instead:

 componentDidMount(){ this.focus(); } 

shouldComponentUpdate : always called before the rendering method and allows you to determine whether re-rendering is necessary or can be skipped. Obviously, this method is never called on initial rendering. It will be called only when a state change occurs in the component.

componentWillUpdate is called as soon as shouldComponentUpdate returns true.

componentDidMount : Once the rendering method has been completed, the componentDidMount function is called. You can access the DOM in this method, allowing you to define DOM operations or data retrieval operations. Any interactions with the DOM should always occur in this case.

Link: https://facebook.imtqy.com/react/docs/react-component.html

+6
source

Set the identifier for input, and then use .setAttribute('autoFocus', true) for the element when you want to focus it

0
source

Source: https://habr.com/ru/post/1015092/


All Articles