/

React Concept: Composition

React Concept: Composition

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:

1
2
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:

1
2
3
4
5
6
7
8
9
10
11
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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:

1
2
3
const Sidebar = props => {
return <aside>{props.children}</aside>
}

And to embed additional components transparently:

1
2
3
4
<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.

tags: [“React”, “composition”, “higher-order components”, “props”]