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
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>'
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With