Reusing code between components in React

Eric Njnaga Dec 29, 2017

Composition

Composition in React is the action of using components as building blocks for other components using the techniques of “containment” or “specialization”.

Containment

Containment is all about creating “empty spots” in a component for any random component to fill.You can use the “children” property of “props” to pass arbitrary children inside components. See the following pen:

You can also pass components as properties of another component. So, you can prepare specific “spots” within a parent component for children components to fill. React elements are object and therefore can be passed in “props”. See pen below:

Specialization

Specialization is about creating a component as template for other components, each new component being slightly different from it parent. You can create a more specific component which renders a more generic one. This is amazing for code reuse and sharing across components. See pen below:

What about Inheritance?

There is no need at this point to use inheritance as “composition” and “props” give all the flexibility needed to customize a component’s look and behaviour in an explicit and safe way.

 

Source of inspiration: React, composition vs inheritance