Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoFocus an input element in react JS

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.

like image 574
Ayan Avatar asked Feb 19 '17 06:02

Ayan


People also ask

How do you autofocus input field in React JS?

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.

How do I use useRef to focus on input?

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.

How do you check input focus in React?

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.


1 Answers

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

like image 102
Mayank Shukla Avatar answered Sep 30 '22 16:09

Mayank Shukla