Skip to content

Files

Latest commit

 

History

History
49 lines (37 loc) · 1.35 KB

higher-order-component.md

File metadata and controls

49 lines (37 loc) · 1.35 KB
id sidebar_label title description keywords version image
higher-order-component
Higher-Order component
Higher-Order Component
Higher-Order component | React Patterns, techniques, tips and tricks in development for Ract developer.
higher-order component
higher order component
reactpatterns
react patterns
reactjspatterns
reactjs patterns
react
reactjs
react techniques
react tips and tricks
Higher-Order components
/img/reactpatterns-cover.png

What is Higher-Order Component?

  • Higher-Order Components in ReactJS is similar to Higher-Order Functions.
  • A higher-order component is a function that takes a component and returns a new component.
  • A higher-order component transforms a component into another component.

For examples

Let's create a HOC that returns the component unaltered.

const withElement = Element => () => <Element />

Let's make this a little bit more useful by adding the property and the color to that element.

const withColor = Element => props => <Element {...props} color="red" />

Then we use this HOC (withColor) in a component.

const Button = () => {
  return <button>My Button</button>
}

const ColoredButton = withColor(Button)

Then we can finally render the ColoredButton component in our app.

function App() {
  return (
    <ColoredButton />
  )
}