Understanding the concept of composition and its importance in React apps
Composition is a fundamental concept in programming that allows you to construct more complex functionality by combining smaller, focused functions.
For instance, when using the map()
function to create a new array from an initial set and then filtering the result using filter()
, composition enables you to perform both actions in a concise and efficient manner:
const list = ['Apple', 'Orange', 'Egg']
list.map(item => item[0]).filter(item => item === 'A') //'A'
In the world of React, composition provides several advantages that can enhance your application development.
Creating Specialized Components
Composition enables you to create smaller, lightweight components and then use them to build more specialized and feature-rich components on top of them. This approach helps in maintaining a modular and reusable codebase. Here’s an example of how to accomplish this:
const Button = props => {
return <button>{props.text}</button>
}
const SubmitButton = () => {
return <Button text="Submit" />
}
const LoginButton = () => {
return <Button text="Login" />
}
Passing Methods as Props
With composition, you can focus on one aspect of functionality within a component while delegating other actions to a container component. By passing methods as props, you can separate concerns and make your code more flexible. Here’s an example:
const Button = props => {
return <button onClick={props.onClickHandler}>{props.text}</button>
}
const LoginButton = props => {
return <Button text="Login" onClickHandler={props.onClickHandler} />
}
const Container = () => {
const onClickHandler = () => {
alert('clicked')
}
return <LoginButton onClickHandler={onClickHandler} />
}
Using Children
The props.children
property in React allows you to inject components into other components seamlessly. To achieve this, the receiving component needs to render props.children
in its JSX. Here’s an example:
const Sidebar = props => {
return <aside>{props.children}</aside>
}
And to embed additional components transparently:
<Sidebar>
<Link title="First link" />
<Link title="Second link" />
</Sidebar>
Higher Order Components
When a component receives another component as a prop and returns a component, it is referred to as a higher-order component. Higher-order components provide powerful reusability patterns in React. To learn more about this topic, you can read my article on React Higher Order Components.