Component Composition with Children
Component Composition with Children is a pattern in React where components are composed together by passing other components or elements as children to a parent component. This allows for greater flexibility and reuse of components, as the parent component can wrap or manipulate the children components without needing to know their specific details.
The two main properties that component composition has;
- Containment
- Specialization
Containment
- Containment is about wrapping or containing child components or elements within a parent component.
- Containment is a technique that is applicable to components that don't know their children ahead of time.
- Example Like a dialogue or a sidebar and that it uses the special children prop two pass elements directly as their content.
import React from "react";
const Card = ({ title, subtitle, children }) => {
return (
<div className="card">
<h2>{title}</h2>
{subtitle && <h3>{subtitle}</h3>}
<div className="card-content">{children}</div>
</div>
);
};
export default Card;
In this example, Card
is a parent component that contains its children (p and button elements) within its layout.
import React from "react";
import Card from "./Card";
const App = () => {
return (
<div>
<Card title="Card Title" subtitle="Card Subtitle">
<p>This is some content inside the card.</p>
<button>Click Me</button>
</Card>
</div>
);
};
export default App;
Specialization
A technique that allows you to define components of special cases of other components, like creating a confirmation dialog based on a dialogue. Then you moved on to a lesson about manipulating children dynamically in JSX.
Here you were introduced to a couple of new react APIs,
React.cloneElement()
(clone and return a new Element)React.Children
(Manipulate children)
React.cloneElement()
returns a new element allowing you to manipulate and transform elements directly in your JSX.React.Children.map()
is useful for children manipulation and that when used in conjunction with react dot clone element enables a powerful composition model for creating flexible components.