MENU
Higher Order Components
A higher-order component is a function that takes a component and returns a new component. This potentially allows us to address cross-cutting concerns.
A HOC doesn't modify the input component, nor does it use inheritance to copy its behavior. Rather, a HOC composes the original component by wrapping it in a container component. A HOC is a pure function with zero side effects.
RESETRUNFULL
RESETRUNFULL
class A extends React.Component {
constructor(props) {
super(props);
}
render() {
return <h1>{this.props.msg}{this.props.data}</h1>;
}}function hoc(WrappedComponent, f){
class MyClass extends React.Component {
constructor(props) {
super(props);
this.state = {name: 'alex'};
}
render() {
const {extra, ...passThroughProps} = this.props;
f("rendering..."+extra); // redering…100
return <WrappedComponent data={this.state.name} {...passThroughProps} />;
}
};
MyClass.displayName = 'MyHOC'; // for easy debugging
return MyClass;}const B = hoc(A, text=>console.log(text));ReactDOM.render(<B msg="hello, " extra="100"/>,document.querySelector("div"));////////////////////////////////////////////////////////////////////////////////////////////////////function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';}console.log(getDisplayName(B)); // MyHOC