Last active
November 7, 2024 13:05
-
-
Save sebmarkbage/ef0bf1f338a7182b6775 to your computer and use it in GitHub Desktop.
Higher-order Components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from "React"; | |
export var Enhance = ComposedComponent => class extends Component { | |
constructor() { | |
this.state = { data: null }; | |
} | |
componentDidMount() { | |
this.setState({ data: 'Hello' }); | |
} | |
render() { | |
return <ComposedComponent {...this.props} data={this.state.data} />; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Enhance } from "./Enhance"; | |
class MyComponent { | |
render() { | |
if (!this.data) return <div>Waiting...</div>; | |
return <div>{this.data}</div>; | |
} | |
} | |
export default Enhance(MyComponent); // Enhanced component |
Wow, the React community really flubbed on terminology here. In this gist, the component utilizing what we call the HoC is called the HoC, whereas the thing we call the HoC is called an "Enhancer." This makes way more sense, as a "HoC," as it is known today, is not itself a component at all. Sad!!
Not quite see the difference between HoC and old decorator pattern. I would say HoC is a nice react implementation of decorator pattern.
Your constructor needs super(props)
as the first line
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
is this the first ever written HOC ?