Skip to content

Instantly share code, notes, and snippets.

@StevenJL
Created January 23, 2016 08:40
Show Gist options
  • Select an option

  • Save StevenJL/041fad8ecf0fb5ca70b1 to your computer and use it in GitHub Desktop.

Select an option

Save StevenJL/041fad8ecf0fb5ca70b1 to your computer and use it in GitHub Desktop.
var CommentForm = React.createClass({
getInitialState: function() {
return {author: '', text: ''};
},
handleAuthorChange: function(e) {
this.setState({author: e.target.value});
},
handleTextChange: function(e) {
this.setState({text: e.target.value});
},
handleSubmit: function(e) {
// since this event originated from a form
// element, it has a default action which
// we want to prevent
e.preventDefault();
var author = this.state.author.trim();
var text = this.state.text.trim();
if (!text || !author) {
return;
}
// sends request to the server
this.setState({author: '', text: ''});
},
render: function() {
return (
/*
The user starts typing their name in the input fields.
This kicks off the onChange handlers defined above
(handleAuthorChange, handleTextChange) which calls setState
which (as mentioned earlier) always calls render, which
will then place the input into the value field.
Afterwards, when the user clicks submit, it invokes
handleSubmit (defined above), which sends the data to the
server and clears the fields.
*/
<form className="commentForm" onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Your name"
value={this.state.author}
onChange={this.handleAuthorChange}
/>
<input
type="text"
placeholder="Say something..."
value={this.state.text}
onChange={this.handleTextChange}
/>
<input type="submit" value="Post" />
</form>
);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment