0
class FlyBehaviour {
  fly = () => {
    // abstract
  };
}

class QuackBehaviour {
  quack = () => {
    // abstract
  };
}

class FlyWings extends FlyBehaviour {

  fly = () => {
    return <p>I can Fly</p>;
  };
}

class NoFly extends FlyBehaviour {
  fly = () => {
    return <p>I cannot Fly</p>;
  };
}

class QuackSound extends QuackBehaviour {
  quack = () => {
    console.log("Quacking");
    return <p>Quack Quack</p>;
  };
}

class Duck extends React.Component {
  constructor(props) {
    super(props);
    QuackBehaviour q; // creating a reference to class QuackBehaviour 
    FlyBehaviour f ;
  }
// some methods that use q and f references
}

This code is just to ask whether can we create references to classes and use them to call their respective methods. Can we do that in React js. If we can, what is the way to do that and if we can't...then why though ?

1 Answer 1

1

Sure, you would simply instantiate a QuackBehavior object.

class Duck extends React.Component {
  constructor(props) {
    super(props);

    this.QuackBehaviour = new QuackBehaviour(); // creating a reference to class QuackBehaviour 
    this.FlyBehaviour = new FlyBehaviour() ;
  }
// some methods that use q and f references
  quack = () => {
    this.QuackBehaviour.quack();
  }
  
  fly = () => {
    this.FlyBehaviour.fly();
  }
}

However, I would strongly advise you to avoid using Class inheritance in React projects.

React favors the composition pattern over the inheritance pattern.

Take a look at this article React – Composition Vs. Inheritance

Sign up to request clarification or add additional context in comments.

1 Comment

@Abdullah Ch did this answer your question?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.