dragonmnl
dragonmnl

Reputation: 15568

React tutorial: CommentForm's onSubmit not working

Tutorial: http://facebook.github.io/react/docs/tutorial.html

var CommentForm = React.createClass({
    handleSubmit: function(e) {
        console.log("form submit");
        e.preventDefault();
        var author = React.findDOMNode(this.refs.author).value.trim();
        var text = React.findDOMNode(this.refs.text).value.trim();
        if (!text || !author) {
            return;
        }
        this.props.onCommentSubmit({author: author, text: text}); // used in CommentBox (callback when the form is sent)
        React.findDOMNode(this.refs.author).value = '';
        React.findDOMNode(this.refs.text).value = '';
        return;
    },
    render: function() {
        return (
            <div className="commentForm" onSubmit={this.handleSubmit}>
                 {/* IMPORTANT: closing each tag is MANDATORY in JSX. e.g. <br/> VS <br>*/}
                <input type="text" placeholder="Your name" ref="author" />
                <input type="text" placeholder="Say something..." ref="text" />
                <input type="submit" value="Post" />
            </div>
        );
    }
});

The form is rendered but when I click on submit nothing happens, not even the console.log.

Upvotes: 4

Views: 3580

Answers (1)

Ryan Huynh.
Ryan Huynh.

Reputation: 306

In the example they use element. When the input submit inside this form is triggered the onSubmit event will be fired. This won't work for Just replace <div> with <form> will fix the problem :)

...
render: function() {
        return (
            <form className="commentForm" onSubmit={this.handleSubmit}>
                 {/* IMPORTANT: closing each tag is MANDATORY in JSX. e.g. <br/> VS <br>*/}
                <input type="text" placeholder="Your name" ref="author" />
                <input type="text" placeholder="Say something..." ref="text" />
                <input type="submit" value="Post" />
            </form>
        );
    }

Upvotes: 2

Related Questions