Reaction concept: composition

What is composition and why is it a key concept in your React application

In programming, composition allows you to build more complex functions by combining small and concentrated functions.

For example, consider usingmap()Create a new array from the initial collection, then use the filtered resultfilter():

const list = ['Apple', 'Orange', 'Egg']
list.map(item => item[0]).filter(item => item === 'A') //'A'

In React, composition gives you some very cool advantages.

You can create small and lean components and use them towriteThere are more functions on top of them. how is it?

Create a dedicated version of the component

Use external components to extend and specialize more general components:

const Button = props => {
  return <button>{props.text}</button>
}

const SubmitButton = () => { return <Button text=“Submit” /> }

const LoginButton = () => { return <Button text=“Login” /> }

Pass method as prop

For example, the component can focus on tracking the click event, and what actually happens when the click event occurs depends on the container component:

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} /> }

Use child

Thisprops.childrenProperties allow you to inject components into other components.

Component needs outputprops.childrenIn its JSX:

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

And you embed more components in it transparently:

<Sidebar>
  <Link title="First link" />
  <Link title="Second link" />
</Sidebar>

High-end components

When a component receives a component as a prop and returns a component, it is called a higher-order component.

You can learn more about high-end components in my articleReact high-end components.

Download mine for freeResponse Handbook


More response tutorials: