React event handlers in Meteor

I’ve started learning React, and in most non-Meteor React examples you can do something like this:

render: function() {
    return (
      <div className="add-player-form">
        <form onSubmit={this.onSubmit}>
          <input type="text" value={this.state.name} onChange={this.onNameChange}/>
          <input type="submit" value="Add Player" />
        </form>
      </div>
    );
  }

But in the Meteor React guides, I keep seeing this:

onClick={this.deleteThisTask.bind(this)}

Why is .bind(this) needed when using React with Meteor, and why wont it work without it?

It’s not a Meteor-React thing, it’s a React thing. Its changed since React updated versions. This article explains it https://medium.com/@housecor/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56#.ypwkmviun

1 Like

Ah ok #1 explains it, I had been using React.createClass({}) when creating components, which autobinds everything. I guess this is being deprecated?

1 Like

Everything is simple.
You need to pass context to function if you want to manipulate state.
Actually, this mechanic has nothing related to Meteor. Its actually just raw JS with context binding.

Simple:

  • Your function doesn’t manipulate state/data/props - you don’t need to bind context.
  • Your function does manipulate state/data/props - you have to bind context.
    In case function won’t have access to “this” overwise

h ok #1 explains it, I had been using
React.createClass({}) when creating components, which autobinds
everything. I guess this is being deprecated?

No, its just another way of react component declaration.

1 Like