Ad

How To Write React Tutorial In ES6 (ES2015)

- 1 answer

I was rewriting the React Tutorial in ES6, and got stuck in tutorial16.js. Whats the proper way to write this es5 in es6 format?

// tutorial16.js
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});
  },
  render: function() {
    return (
      <form className="commentForm">
        <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>
    );
  }
});

Here is my CommentForm.jsx that I've written in ES6. If I try to type anything in the form, I get this message in the console: Uncaught TypeError: Cannot read property 'setState' of undefined What I'm doing wrong?

import React from 'react';

class CommentForm extends React.Component {

    constructor(props){
        super(props);
        this.state = { author: '', text: '' }
    }

    handleAuthorChange(e){
        this.setState({author: e.target.value});
    };

    handleTextChange(e){
        this.setState({text: e.target.value});
    }

    render(){
        return(
            <form className="commentForm">
                <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>
        );
    }
}

export default CommentForm;
Ad

Answer

You are missing binding onChange handlers to the instance. They are being fired in totally different context, where this doesn't point to your CommentForm.

It should be instead:

<input onChange={this.handleAuthorChange.bind(this)} type="text" placeholder="Your name" value={this.state.author} />
<input onChange={this.handleTextChange.bind(this)} type="text" placeholder="Say something..." value={this.state.text} />
Ad
source: stackoverflow.com
Ad