Home > front end >  How i can call the function of other component?
How i can call the function of other component?

Time:01-17

I have two classes:

class A extends Component {
   callMyFunction = () => {

   }
}

class B extends Component {
   callOtherFunction = () => {
      A.callMyFunction(); // It doesnt works
   }
}

How to call this from class B in otherFunction?

CodePudding user response:

Well, the specifics do matter. Because there would be different ways of doing this depending on how the two components interact with each other.

If class A is not a child component of class B (meaning you are not rendering class A inside of class B), then you can just import callMyFunction in the class B file.

import { callMyFunction } from '[relativePathToClassA]'

Then you can call callMyFunction pretty much wherever inside of class B.

class B extends Component {
   callOtherFunction = () => {
      callMyFunction()
   }
}

I do not usually work with class components so there may be some nuance there that I am leaving it but this is the general idea.

I will leave my answer there because I believe this should give you what you want based on the limited information provided in your question. If not, feel free to elaborate by responding to @codemonkey's comment and I can explain more as well.

  •  Tags:  
  • Related