Composition vs Inheritance

Tram Ho

Composition vs Inheritance

Na is this article we will compare the two concepts “Ingredients” and “Inheritance”.

One of React’s strengths is its design in the “component” direction, subdividing the application into multiple components, and React also recommends developing the application in the direction of “Components” rather than “Inheritance” to facilitate More convenient for reuse between components.

In this article, we will explore some issues related to inheritance and how to solve problems by breaking down into “Components”.

Containment

While working on a project we may encounter some components that they do not yet have details that depend on the passed properties. For example, some basic components are designed to be used in many places.

For example, 2 Component Sidebar or Dialog , 2 Components will have different content on each screen and will depend on what is passed to them.

And in React to solve this problem, the manufacturer recommended using a special prop, called children to pass the element to the Component.

And this component will be used as follows:

For example here

As in the above example, everything wrapped in FancyBorder tags is collected into prop children and when Render, FancyBorder component will render children into a Div tag as in the above example.

It is a simple example of sending a content to the Component, but in reality we sometimes need to pass more content into how.

In such cases, you can set your own conventions and pass them on as a custom prop instead of using prop children

See an example

In the above example, the two components <Contact /> and <Chat/> are 2 objects, and you can pass it into the other Component as other data types. One of React’s strengths is this,

  • You are not limited in the number of props passed into each component
  • You declare and pass into the Component object, you will find it in this.props

Specialization

In React, we aim to split Application of the Thành Phần Where separate component has many similarities.

Turn to the FancyBorder Component example.

Now we need a component like this:

  • It is a Component like FancyBorder
  • It can change data based on input

See an example here .

Breaking down into smaller components is convenient and can be used in many places, such as in a class

See an example

So What About Inheritance?

One of the biggest applications built with React is Facebook, it works on a combination of thousands of small components, and so far Facebook developers have not found any Component cases yet. use inheritance.

With props and splitting the Application into multiple components, it will give you flexibility to handle your Components. And always remember that Component can accept any props including basic values, React Element, or maybe a function.

Also, if you want to use functions between components, you only need to Export, and Import without having to extend

Share the news now

Source : Viblo