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 components |
/img/reactpatterns-cover.png |
- 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.
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 />
)
}