Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set focus on an input field after rendering?

What's the react way of setting focus on a particular text field after the component is rendered?

Documentation seems to suggest using refs, e.g:

Set ref="nameInput" on my input field in the render function, and then call:

this.refs.nameInput.getInputDOMNode().focus();  

But where should I call this? I've tried a few places but I cannot get it to work.

like image 833
Dave Avatar asked Mar 05 '15 23:03

Dave


People also ask

How do you set the focus on an input field?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.

What is focus () in React?

focus() with React. The . focus() method tells the browser which element is being acted on, similar to . click() or an actual click.

How do you focus input in functional component?

If you add React to an existing application and render a component into a detached element, React will call focus() before the browser is ready, and the input will not be focused when it gets added to the DOM. So, instead of depending on React to call focus() on the input, we are going to do it ourselves.


1 Answers

@Dhiraj's answer is correct, and for convenience you can use the autoFocus prop to have an input automatically focus when mounted:

<input autoFocus name=... 

Note that in jsx it's autoFocus (capital F) unlike plain old html which is case-insensitive.

like image 119
Brigand Avatar answered Oct 09 '22 07:10

Brigand