React.js Higher Order Components
Reactjs Higher-Order Components also known as hoc is a function that takes a component and produces a new component.
const EnhancedComponent = higherOrderComponent(WrappedComponent);
It wraps around a normal component and gives additional data input. It is a technique to reuse component logic. HOCs are not part of React API. They are patterns that arise from React’s compositional nature. Components transform props into UI and HOC converts components to another component. Let’s analyze through an example.
import React from 'react';
var newData = {
data: 'Data from HOC...',
}
var MyHOC = ComposedComponent => class extends React.Component {
componentDidMount() {
this.setState({
data: newData.data
});
}
render() {
return <ComposedComponent {...this.props} {...this.state} />;
}
};
class MyComponent extends React.Component {
render() {
return (
<div>
<h1>{this.props.data}</h1>
</div>
)
}
}
export default MyHOC(MyComponent);
In our example MyHOC is an HOC function that we use to pass data to MyComponent. The function takes the component and returns it along with newData. When we run the app it will display the following result.
Data from HOC
sam smith
16 Apr 2023
I just want the whole world to know about this spell caster I met two weeks ago, I cannot say everything he has done for me my wife left me 3 years ago left with my kids I was going through online when I meant this wonderful man's testimony online I decided to give it a try and my wife is back to me now and we are happily married again cause is too much to put in writing all I can say is thank you very much am very happy Contact him today on oseremenspelltemple@gmail.com or whatsapp him on +2348136482342. www.facebook.com/Dr-odion-spell-temple-110513923938220