Components composition in react

Components composition in react

#30 days of react

·

2 min read

Defining component composition

Component composition is a pattern in which you pass components as a prop to another component.

If you build react applications, you probably already do this without knowing what it is called. Components in react applications allow you to accept props, think about how a regular function in javascript allows you to accept arguments and parameters. Now instead of passing in values as a prop between components, the composition is a pattern where you pass another component as a prop.

In the code sample below, I have created a Button component

export const Button = ({ action, children }) => {
    return <button onClick={action}>{children}</button>
}

This Button component can now be imported and used in my App (or any other) component.

import {Button} from './components/Button';

const App = () => {
    const handleClick = () => console.log('click clack')

     return (
       <h1> Component composition </h1>
       <Button action={handleClick}> Click me! </Button>
   )
}

The children props allow us to pass anything into the Button component. In the example below, we have added an icon

import {Button} from './components/Button';

const App = () => {
    const handleClick = () => console.log('click clack')

     return (
       <h1> Component composition </h1>
       <Button action={handleClick}> 
              Danger
              <i class="fa fa-ban" aria-hidden="true"></i>
       </Button>
   )
}

This pattern makes our react components more reusable. If you had to build an application with the same button but different use cases: error, alert, success, etc. You can decide to build a single component Button, style them differently and pass different actions to them using the props.

Component composition can be used to improve application performance and avoid prop drilling, read more on the subject here

Additional resource:

  1. Pass a component as props in react
  2. React component as props: the right way
  3. React component composition explained
  4. visual learners
  5. From the react documentation