Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 279
tuna Avatar asked Nov 27 '14 13:11

tuna


People also ask

How do you pass a function via props in React?

To pass a function as props in React TypeScript: Define a type for the function property in the component's interface. Define the function in the parent component. Pass the function as a prop to the child component.


1 Answers

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)}
like image 108
Brigand Avatar answered Sep 20 '22 12:09

Brigand