Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear an input field with Reactjs?

I am using a variable below.

var newInput = {    title: this.inputTitle.value,    entry: this.inputEntry.value     }; 

This is used by my input fields.

<input type="text" id="inputname" className="form-control" ref={el => this.inputTitle = el} />    <textarea id="inputage" ref={el => this.inputEntry = el} className="form-control" /> <button className="btn btn-info" onClick={this.sendthru}>Add</button> 

Once I activate {this.sendthru} I want to clear my input fields. However, I am uncertain how to do so.

Also, as shown in this example, it was pointed out to me that I should use the ref property for input values. What I am unclear of is what exactly does it mean to have {el => this.inputEntry = el}. What is the significance of el in this situation?

like image 757
Jason Chen Avatar asked Aug 02 '16 22:08

Jason Chen


People also ask

How do you clear the input field in text?

To clear an input field after submitting:When the button is clicked, set the input field's value to an empty string. Setting the field's value to an empty string resets the input.

How do you clear the input field in HTML?

To clear all the input in an HTML form, use the <input> tag with the type attribute as reset.


2 Answers

Let me assume that you have done the 'this' binding of 'sendThru' function.

The below functions clears the input fields when the method is triggered.

sendThru() {     this.inputTitle.value = "";     this.inputEntry.value = ""; } 

Refs can be written as inline function expression:

ref={el => this.inputTitle = el} 

where el refers to the component.

When refs are written like above, React sees a different function object each time so on every update, ref will be called with null immediately before it's called with the component instance.

Read more about it here.

like image 107
Galeel Bhasha Avatar answered Sep 19 '22 07:09

Galeel Bhasha


Declare value attribute for input tag (i.e value= {this.state.name}) and if you want to clear this input value you have to use this.setState({name : ''})

PFB working code for your reference :

<script type="text/babel">     var StateComponent = React.createClass({         resetName : function(event){             this.setState({                 name : ''             });         },         render : function(){             return (                 <div>                     <input type="text" value= {this.state.name}/>                     <button onClick={this.resetName}>Reset</button>                 </div>             )         }     });     ReactDOM.render(<StateComponent/>, document.getElementById('app')); </script> 
like image 36
Satheesh Avatar answered Sep 18 '22 07:09

Satheesh