Component Composition
In React, component composition refers to the technique of combining smaller components together to build larger and more complex components.
Think of component composition as a way of building a hierarchy of reusable building blocks. Each component represents a specific functionality or feature, and by composing them together, we can create powerful and flexible UIs.
Let's consider an example to better understand component composition. Suppose we want to build a basketball scoreboard component in React. The scoreboard component will display the scores of two teams: the Lakers and the Raptors.
To implement this, we can create smaller components for each team's score and then compose them inside a parent component called Scoreboard
.
Here's an example implementation:
1import React from 'react';
2
3function Scoreboard() {
4 return (
5 <div>
6 <h2>Scoreboard</h2>
7 <TeamScore teamName="Lakers" score={98} />
8 <TeamScore teamName="Raptors" score={102} />
9 </div>
10 );
11}
12
13function TeamScore({ teamName, score }) {
14 return (
15 <div>
16 <h3>{teamName}</h3>
17 <p>Score: {score}</p>
18 </div>
19 );
20}
21
22export default Scoreboard;
In this example, the Scoreboard
component is the parent component that contains two instances of the TeamScore
component. Each TeamScore
component displays the team name and score.
By composing the TeamScore
components inside the Scoreboard
component, we can build a complete scoreboard UI that renders the scores of both teams.
This technique of component composition allows us to break down complex UIs into smaller and more manageable components. We can reuse these smaller components in multiple places of our application and easily update or modify them as needed.
Component composition is a powerful concept in React that promotes reusability and modular development. It enables us to build complex UIs by combining simple and independent building blocks.
xxxxxxxxxx
// Let's suppose we want to build a simple basketball scoreboard component in React.
import React from 'react';
function Scoreboard() {
return (
<div>
<h2>Scoreboard</h2>
<TeamScore teamName="Lakers" score={98} />
<TeamScore teamName="Raptors" score={102} />
</div>
);
}
function TeamScore({ teamName, score }) {
return (
<div>
<h3>{teamName}</h3>
<p>Score: {score}</p>
</div>
);
}
export default Scoreboard;