In all major programming languages there are few really great concepts like inheritance, abstraction, polymorphism, etc.
React has another concept called “composition”.
Now, the basic meaning of composition is nothing but a mixture of few ingredients which is actually works great since in React, the whole app is divided into small components and when they come all together, they make the app complete. But that’s just a basic understanding.
React has actually a powerful composition model. React recommends using composition rather than inheritance to reuse the code between different components.
So, what is Containment?
Some generic “boxes” components like Sidebar or a Dialog box in React are not aware of their children ahead of time. In those cases, React recommends that those components use their special children props to pass the children elements into their output.
Just like this:
function QuoteContainer(props) {
return (
{props.children}
);
}
So that the other components can nest the JSX by passing the arbitrary children.
Just like this:
function Quote() {
return (
Some Quote
-by Yogesh Chauhan
);
}
Pay attention to the QuoteContainer inside the Quote() component. Whatever you add inside QuoteContainer, it will be passed to the Quote(). The Quote() receives the props and renders them inside a div with classes that are defined in the stylesheet. At the end, the whole picture comes together and makes the final output.
Specialization in React
We want to use specialization in cases where we want to make some components act “specially”.
That’s where the composition comes into play.
Composition in React happens when a special component renders a generic component and then configures it with the passed props.
Let’s change the example above to understand this.
Specialization Demo
components composition containment examples Inheritance specialization