Home > Software engineering >  call a function from another class in react
call a function from another class in react

Time:04-01

I'm still new to react I need help in calling a function from another class/file. Also I want to use the states from the class1 file.

in short, this are the codes:

function in Class1

endCall() {
    endCall(this.state.currentCallRoom);
    this.setState(
      {
        isCallOngoing: false,
        currentCallRoom: null,
        notification: null,
      },
      () => console.log("Call ended")
    );
  }

div in Class2

 <div className={s.IconContainer}>
              <IconButton className={s.topIcon} onClick={() => this.endCall()}>
                <CallEnd className={s.icon} style={{color: "red"}}/>
                <text className={s.text}>EndCall</text>
              </IconButton>
            </div>

does anyone have any idea how i can use the method from class1?

CodePudding user response:

Your code isn't very clear. I suggest to move endCall function to class1 and class2's parent component, and also manage State in the parent component as well, then pass the function and any data you need as props to class1 and class2. Also suggest a readthrough of this article Lifting State Up. Hope this may help.

CodePudding user response:

import { foo_function } from './your-file-name'

move your function outside the class and import this way

  • Related