Barna Kovacs
Barna Kovacs

Reputation: 1276

How to pass function groups as props in React?

I use this simple React component only for example.

I would like to access this.setState() inside the functions 'working' and 'group.notWorking'.

var myComponent = React.createClass({
  getInitialState: function() {
    return {};
  },

  working: function() {
    this.setState({ test: true });  //this is myComponent
  },

  group: {
    notWorking: function() {
      console.log(this); //this is window
    }
  },

  render: function() {
    return (
        <div>
          <ChildComponent working={this.working} group={this.group}/>
        </div>
    );
  },
});

My question is how do you pass functions grouped in an object, or is there any best practice, to avoid passing all the functions one by one to children components.

Upvotes: 2

Views: 1154

Answers (1)

nanobar
nanobar

Reputation: 66445

You need to pass a bound version of it.

<ChildComponent working={this.working} group={this.group.notWorking.bind(this)}/>

If you want to pass the whole group you need to make it a function which returns an object and bind it:

group: function() {
    return {
        notWorking: function() {
          console.log(this);
        }.bind(this)
    };
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

Upvotes: 3

Related Questions