tuna
tuna

Reputation: 6351

Reactjs passing methods as props to child

Is there a way to pass methods of current class to child class as props

As an example;

var SignupModal = React.createClass({
mixins: [CheckMixin],
getInitialState: function(){
  return {
      'wizardstate': 0
  }
},
setWizardState: function(state){
    var that = this;
    switch (state){
        case 0:
           that.setState({'wizardstate': 0});
           break;
        case 1:
            that.setState({'wizardstate': 1});
            break;
        case 2:
            that.setState({'wizardstate': 2});
            break;
        case 3:
            that.setState({'wizardstate': 3});
            break;
        case 4:
            that.setState({'wizardstate': 4});
            break;
    }
},
render: function(){
    var temp;
    switch (this.state.wizardstate){
        case 0:
           temp = (<SignupSetup setWizardState={this.setWizardState}/>);
            break;
        case 1:
            temp = (<EmailSetup />);
            break;
        case 2:
            temp = (<PasswordSetup />);
            break;
        case 3:
            temp =  (<UsernameSetup />);
            break;
        case 4:
            temp = (<CategoriesSetup />);
            break;
    }
    return (<Modal {...this.props} title="Login" animation={false}>
            <div className="modal-body">
                <div>
                {temp}
                </div>
            </div>
        </Modal>)


var SignupSetup = React.createClass({
    render: function(){
        return (<Button onClick={this.props.setWizardState(1)}></Button>)
    }
});

I want to pass this setWizardState method of SignupModal to child SignupSetup as prop, but i get the error

Uncaught Error: Invariant Violation: replaceState(...): Cannot update during an existing state transition (such as withinrender). Render methods should be a pure function of props and state.react.js:17122

Upvotes: 13

Views: 9324

Answers (3)

Brigand
Brigand

Reputation: 86260

The problems are here:

<Button onclick={this.props.setWizardState(1)}></Button>

First is a typo (onClick, capital C). But the main problem is that you're calling setWizardState, and onClick takes a function. You need to partially apply it.

onClick={this.props.setWizardState.bind(null, 1)}

Upvotes: 17

Zhehao Victor Zhou
Zhehao Victor Zhou

Reputation: 203

Here's a link at official reactjs website. Apparent you need bind this function instead of directly apply.

onClick={this.setWizardState.bind(this, 1)}

Upvotes: 0

Omar Meky
Omar Meky

Reputation: 606

You can also use es6 arrow notation if you have a compiler like Babel

<Button onclick={() => this.props.setWizardState(1)}></Button>

Upvotes: 6

Related Questions