Search code examples
javascriptreactjstypescriptreact-component

How to call a function defined inside react component in a typescript class?


 export class abc extends React.Component<IProps, IState> {
    function(name: string) {
    console.log("I wish to call this function"+ name);
    }

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

Now I wish to call the function method of the above-defined component into another xyz.ts class (which is not a react component) is it possible to do the same?


Solution

  • You could use the listener pattern like this:

    export interface IListener {
        notify: (name:string) => void;
    }
    
    
    export class Listener {
        listener : IListener[] = [];
    
    
        addListener(listener: IListener) {
          this.listener.add(listener)
        }
    
        notifyListener() {
          this.listener.forEach((listener) => {
              listener.notify("abc");
          });
        }
      }
    
      export class abc extends React.Component<IProps, IState> implements IListener {
    
        componentDidMount() {
            // register this class as a listener
            new Listener().addListener(this);
        }
    
        public notify(name:string) {
            this.test(name);
        }
    
        test(name: string) {
          console.log("I wish to call this function"+ name);
        }
        render() {
          return (
          <div>Hello</div>);
        }
        
      }