Monday

React: calling a function from a string using Typescript

Example of calling functions(in actions.ts) by giving string name dynamically with the same input parameters.

actions.ts
export function actionExampleFirst(data: any) {
  console.log('actionExampleFirst has called. parameters: ' + data);
}

export function actionExampleSecond(data: any) {
  console.log('actionExampleSecond has called. parameters: ' + data);
}

callActionsDynamically.tsx
import React from 'react';
import * as actions from './actions';

interface IProp {
}

type ActionType = typeof actions;

class CallActionsDynamically extends React.PureComponent<IProp> {
  constructor(props: IProp) {
    super(props);
    this.dynamicCall = this.dynamicCall.bind(this);
  }

  componentDidMount() {
    this.dynamicCall('actionExampleSecond', 'some parameters 2');
    this.dynamicCall('actionExampleFirst', 'some parameters 1');
  }

  dynamicCall<K extends keyof ActionType>(funcName: K, data: any) {
     actions[funcName](data);
  }

  render() {
    return(
      <></>
    );
  }
}

export default CallActionsDynamically;

You will see in the console:
actionExampleSecond has called. parameters: some parameters 2
actionExampleFirst has called. parameters: some parameters 1

No comments:

Post a Comment