YogeshChauhan . com

What does Containment mean in React?

in React on May 27, 2021

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 (
    <div className={'Quote Quote-' + props.color}>

So that the other components can nest the JSX by passing the arbitrary children.

Just like this:

function Quote() {
  return (
    <QuoteContainer color="red">
        Some Quote
        -by Yogesh Chauhan

Here’s the working demo:

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


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

What is Hoisting in JavaScript?JavaScriptSQL Left JoinSQL/MySQL3 Common Usability Mistakes In Web DesignUI/UXFor Each Loop in Swift for BeginnersSwiftHow to create a new HTML element programmatically using JavaScript?HTMLSafe Practice to add Links to cross-origin destinationUI/UX