Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call dynamically methods in React

I'm trying to call a few methods dynamically in my React component.

so I have this code where I want to call a function stepOne, stepTwo, etc. whenever that step is achieved, but this needs to be dynamically called to add new steps in the future.

However I tried already a couple of methods (hasOwnProperty,typeof this[methodName], this.{methodName}()) and can't get to call the right method.

Here is my code:

class MyComponent extends React.Component<Props,State>{

    steps = [
        'stepOne',
        'stepTwo',
        'stepThree',
    ];

    state = {step:1};

    stepOne(){
        return 'This is Step One';
    }

    stepTwo(){
        return 'This is Step Two';
    }

    _getContent(){
        let content = 'Step not exists';

        const methodName = this.steps[this.state.step - 1];

        if (typeof this[methodName] === 'function') {
            content = this[methodName]();
        }
        return content;
    }

    render(){
        return '<div>' + this._getContent() + '</div>'
    }
}

In this example, I always get undefined in the typeof this[methodName] operation

like image 731
Abraham Romero Avatar asked Mar 06 '23 17:03

Abraham Romero


1 Answers

Try creating the map of functions and bind this context to your created functions

class MyComponent extends React.Component<Props,State>{
    constructor(props){
        super(props);
        this.stepOne = this.stepOne.bind(this);
        this.stepTwo = this.stepTwo.bind(this);
        this.funcMap = {
            '1': this.stepOne,
            '2': this.stepTwo
        };
        this.state = {step: '1'};
    }


    stepOne(){
        return 'This is Step One';
    }

    stepTwo(){
        return 'This is Step Two';
    }

    _getContent(){
        let content = 'Step not exists';

        const method = this.funcMap[this.state.step];

        if (typeof method === 'function') {
            content = method();
        }
        return content;
    }

    render(){
        return '<div>' + this._getContent() + '</div>'
    }
}
like image 147
Suresh Prajapati Avatar answered Mar 12 '23 07:03

Suresh Prajapati