Last active
September 9, 2016 08:45
-
-
Save bspaulding/8463d6021e1df2f7e248db0b6de5a28b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| function Nce(max, Component) { | |
| var n = 0; | |
| return class extends React.Component { | |
| constructor(props) { | |
| super(props); | |
| n += 1; | |
| this.n = n; | |
| } | |
| render() { | |
| return this.n <= max | |
| ? <Component {...this.props}/> | |
| : null; | |
| } | |
| } | |
| } | |
| function Once(Component) { | |
| return Nce(1, Component); | |
| } | |
| /* Example Usage */ | |
| const Highlander = ({ n }) => <div>Highlander #{n}</div>; | |
| const OnlyOne = Once(Highlander); | |
| ReactDOM.render( | |
| <div> | |
| <OnlyOne n="1"/> | |
| <OnlyOne n="2"/> | |
| <OnlyOne n="3"/> | |
| <OnlyOne n="4"/> | |
| <OnlyOne n="5"/> | |
| </div>, | |
| document.getElementById('container') | |
| ); | |
| /* HTML Result | |
| <div class="container"> | |
| <div data-reactroot> | |
| <div>Highlander #1</div> | |
| <!-- react empty 5 --> | |
| <!-- react empty 6 --> | |
| <!-- react empty 7 --> | |
| <!-- react empty 8 --> | |
| </div> | |
| </div> | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment