Created
October 11, 2017 16:30
-
-
Save danieluhl/2368811be6d62dbca0dc98f2b6b2ab3a to your computer and use it in GitHub Desktop.
Simple HOC vs Render Props (function as children) Example
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
<!doctype html> | |
<html> | |
<head> | |
<title>unpkg-demos :: global-react</title> | |
</head> | |
<body> | |
<div id="app"></div> | |
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js" | |
integrity="sha384-lJJbYsDe7wDuOttI/MIHfj68o3fVZOhJDxEn0cTPbDq5mkzjF1p+AFEp3r/HpUnt" | |
crossorigin="anonymous"></script> | |
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js" | |
integrity="sha384-urrH8a5NtX87DSmFO4pKPICl5RHszNM6yx75JIYhynT2ukWDK4skf0YAh4EDEdD2" | |
crossorigin="anonymous"></script> | |
<script src="https://unpkg.com/[email protected]/babel.min.js" charset="utf-8"></script> | |
<script src="https://unpkg.com/[email protected]/dist/redux.min.js"></script> | |
<script src="https://unpkg.com/[email protected]/dist/react-redux.min.js"></script> | |
<style> | |
.error { | |
border: 1px solid #c00; | |
} | |
.valid { | |
border: 1px solid #0c0; | |
} | |
</style> | |
<script type="text/babel"> | |
/** | |
* Render Prop pattern | |
* A component that has a property that is a function used to render | |
* https://github.com/facebook/react/pull/10741 | |
*/ | |
const ValidatedHello = ({children, val}) => { | |
return (children(val > 10)); | |
}; | |
const Hello = () => <h1>Hello, World!</h1>; | |
const App = ({val}) => <ValidatedHello val={val}> | |
{ | |
(isValid) => | |
<div className={isValid ? 'valid' : 'error'}><Hello /></div> | |
} | |
</ValidatedHello> | |
ReactDOM.render(<App val={20} />, document.getElementById('app')); | |
/** | |
* Higher Order Component pattern | |
* Is a function that accepts a Component as an argument and returns a Component. | |
*/ | |
// const withValidation = (WrappedComponent) => ({val}) => { | |
// return ( | |
// <WrappedComponent isValid={val > 10} /> | |
// ); | |
// } | |
// const Hello = ({isValid}) => { | |
// return (<div className={isValid ? 'valid' : 'error'}><h1>Hello, World!</h1></div>); | |
// } | |
// const ValidatedHello = withValidation(Hello); | |
// const App = ({val}) => <ValidatedHello val={val} />; | |
// ReactDOM.render(<App val={2} />, document.getElementById('app')); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment