I'm making a comment form with React. I've almost built what I want except this little issue, where I'm not able to clear my input value, after I submit the form. What I typed in stays in the input field even after submitting.
My code:
CommentsIndex.js
class CommentsIndex extends React.Component {
constructor(props) {
super(props);
this.state = {
url: this.props.url,
comment: '',
};
this.onSubmit2 = this.onSubmit2.bind(this);
}
loadCommentsFromServer() {
$.ajax({
// ajax call working fine
});
}
onSubmit2(value) {
const url = this.props.url;
$.ajax({
url: url,
dataType: 'text',
type: 'POST',
cache: false,
data: {
comment: value
},
success: (data) => {
this.loadCommentsFromServer();
},
error: (xhr, status, err) => {
console.error(url, status, err.toString());
},
});
}
componentDidMount() {
this.loadCommentsFromServer();
}
render() {
return (
<div>
<NewComment onSubmit1={this.onSubmit2} />
<Comments comments={this.state.comments} />
</div>
);
}
}
export default CommentsIndex;
NewComment.js
class NewComment extends React.Component {
constructor(props) {
super(props);
this.state = {
comment: ''
};
this.getInput = this.getInput.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
getInput(e) {
this.setState({
comment: e.target.value
});
}
onSubmit() {
this.props.onSubmit1(this.state.comment);
}
render() {
return (
<div>
<input className="comment-field" onChange={this.getInput} />
<input className="comment-submit" type="submit" value="SUBMIT" onClick={this.onSubmit} />
</div>
);
}
}
export default NewComment;
I tried adding this.setState({ value: '' })
inside success: (data) => {}
in my onSubmit2()
, but it didn't work.
Any advise would be appreciated. Thanks in advance!