I have the following form component in a skylight dialog, after submit, if the dialog is reopened containing the form, it contains the previous submitted value. Can anyone please tell me how to stop this and clear the textarea value everytime the dialog is opened?
Here is my component:
var AddNoteForm = React.createClass({
componentDidMount: function() {
React.findDOMNode(this.refs.notes).value = "";
},
handleSubmit: function (event) {
event.preventDefault();
var notes = React.findDOMNode(this.refs.notes).value;
var details = {
studentId: this.props.studentId,
schoolId: this.props.schoolId,
notes: notes
};
this.props.onSubmit(details);
},
render: function() {
return (
<form className="pure-form pure-form-aligned"
onSubmit={this.handleSubmit}>
<div className="pure-control-group">
<label htmlFor="notes">Note</label>
<textarea ref="notes" id="notes" placeholder="Note..." >
</textarea>
</div>
<div className="pure-controls">
<input type="submit" value="Save" />
</div>
</form>
);
}
});
module.exports = AddNoteForm;
The solution is to use the reset() function from the React Hook Form library, if you execute the function without any parameters ( reset() ) the form is reset to its default values, if you pass an object to the function it will set the form with the values from the object (e.g. reset({ firstName: 'Bob' }) ).
To clear the value of a textarea element, set it's value property to an empty string, e.g. textarea. value = '' . Setting the element's value to an empty string removes any of the text from the element.
Resetting States to Initial State Then we call useState in App to create the object state. Next, we create the clearState function to reset the state by calling the setState state setter function with a copy of the initialState . Making a copy lets React know that it has to update the state and re-render.
take e for event as a parameter in onSubmit function. then use e. target. reset(); at the end of function.
so if some one stuck in this problem , I was using uncontrolled component and it is somehow complex to clear it, I just change to controlled one and then got it :)
<form onSubmit={e => this.handleSubmit(e)}>
<textarea value={this.state.text} onChange={ e => this.handleChange(e) } />
<button>Submit Comment</button>
</form>
very important to prevent default
handleSubmit = event => {
event.preventDefault();
this.setState({ text: '' });
};
Basically your form is not getting unmounted. So writing the code in componentDidMount will not make sense. So the quick fix for your problem would be to clear the textarea box after you read the value in handle submit method
handleSubmit: function (event) {
event.preventDefault();
var notes = this.refs.notes;
var details = {
studentId: this.props.studentId,
schoolId: this.props.schoolId,
notes: notes.value
};
notes.value = ""; // Unset the value
this.props.onSubmit(details);
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With