-1

I am trying to convert class component to functional component, but having a trouble calling method 'resize' of child component 'Dog.js'

  1. App.js
function App(props) {
  useEffect(() => {
    const dogs = [
      new Dog("#fff", 1, 2)
    ]

    dogs[0].resize(stageWidth, stageHeight) // here is what I want to perform - now it is undefined

   },[])
 ...
 }

  1. Dog.js

function Dog(color, speed, total) {

  Dog.resize = (stageWidth, stageHeight) => {
      const gap = Math.ceil(stageWidth / (this.total - 2));
      ...
  };

}
export default Dog;

please let me know how to use the 'resize' method of Dog.js in App.js, or what i need to change in my code structure. (or just keeping the structure of class component is better?)

hs L
  • 13
  • 3
  • 1
    Does this answer your question? [Call child method from parent](https://stackoverflow.com/questions/37949981/call-child-method-from-parent) – Vikas Dec 02 '20 at 08:30
  • 1
    Is `Dog` supposed to be a React component? If so, it isn't valid React component. React components accept a single props object. React components also do not reach into other react components to invoke functions. Can you provide more details about what you are trying to accomplish? – Drew Reese Dec 02 '20 at 08:34

1 Answers1

1

To call resize Dog.js method from App.js you need to change Dog function like this:

function Dog(color, speed, total) {

  this.resize = (stageWidth, stageHeight) => {
      const gap = Math.ceil(stageWidth / (this.total - 2));
      ...
  };

}
export default Dog;
Junior Ngangeli
  • 112
  • 1
  • 7