2

I have this simple form on React js

 render: function(){    
    return (
        <div>                                   
            <form onSubmit={this.hanldeSubmit} >
                <input 
                    type='text' placeholder='What do you need to do?' required
                    onChange={this.handleChange} value={this.state.value}   
                />
                <button className='button expanded'>Add Todo</button>
            </form>
        </div>  
    );
}

Here is the on submit handler. I want to set focus on input field. Please tell me the more right way doing this in controlled component WITHOUT refs:

 hanldeSubmit: function(e){
    e.preventDefault();
    var {value} = this.state;
    if(value){
        this.props.onAddTodo(value);
        this.setState({value: ''});
    }

    //how to set focus on input field?      
},

I found this code with refs:

 this.refs.todoText.focus()

Thanks in advance

UPDATE:


Ok if I use refs to set focus:

this.refs.yourInputBox.focus();

Should I keep my component being 'controlled' ? What is the 'best practice'?

1 Answer 1

3

You can use this in your input box to set default autoFocus to that input also set a ref value for the input box.

<input 
 type='text' ref="yourInputBox" placeholder='What do you need to do?'
 onChange={this.handleChange} value={this.state.value}
 autoFocus   
/>

Use this in the else condition which is needed.

 hanldeSubmit: function(e){
   e.preventDefault();
   var {value} = this.state;
   if(value){
      this.props.onAddTodo(value);
      this.setState({value: ''});
   }
   else{
      this.refs.yourInputBox.focus();
   }
 }

try this hope it works

Sign up to request clarification or add additional context in comments.

8 Comments

thank you very much. As I understand it sets focus after render method called. But how to set focus after submitting the form with empty field?
I believe even after form submission autoFocus will remain. If you do not want to submit an empty field just type in this into your input box
'<input type='text' placeholder='What do you need to do?' onChange={this.handleChange} value={this.state.value} autoFocus required />'
Thank you very much for your answers. But the focus will doesn't remain after submission.
I updated my question - how to set focus in handleSubmit in any way - weather valid or invalid data
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.