Luis Dos Reis
Luis Dos Reis

Reputation: 393

ReactJS issue: () => vs function ()

Was following along the ReactJS tutorial from their website.

var Comment = React.createClass({
  render: function() {
    return (
      <div className="comment">
        <h2 className="commentAuthor">
          {this.props.author}
        </h2>
        {this.props.children}
      </div>
    );
  }
});

var CommentList = React.createClass({
  render: () => {
    return (
      <div className="commentList">
        <Comment author="Pete Hunt">This is one comment</Comment>
        <Comment author="Jordan Walke"> This is *another* comment</Comment>
      </div>
    );
  }
});

var CommentForm = React.createClass({
  render: () => {
    return (
      <div className="commentForm">
        Comment Form
      </div>
    );
  }
});

var CommentBox = React.createClass({
  render: () => {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList />
        <CommentForm/>
      </div>
    );
  }
});

ReactDOM.render(
  <CommentBox />,
  document.getElementById("content")
);

However, if I use arrow notation in the first component Comments, namely:

(*params*) => {}

instead of the normal function declaration notation, namely:

function(*params*) {}

The chrome interpreter will spit out the following error:

Uncaught TypeError: Cannot read property 'props' of undefined


Can anyone shine some light on the matter?

Upvotes: 0

Views: 217

Answers (1)

poke
poke

Reputation: 387607

Arrow functions will not bind this. So if you create your render function as an arrow function, the this will not be bound to the current component.

So, for render and other methods that belong to your component and need access to the component as this, you need to use real functions. You can use arrow functions for nested functions though (and there it makes more sense to use them).

Upvotes: 4

Related Questions