Skip to content

Instantly share code, notes, and snippets.

@danieluhl
Created October 11, 2017 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danieluhl/2368811be6d62dbca0dc98f2b6b2ab3a to your computer and use it in GitHub Desktop.
Save danieluhl/2368811be6d62dbca0dc98f2b6b2ab3a to your computer and use it in GitHub Desktop.
Simple HOC vs Render Props (function as children) Example
<!doctype html>
<html>
<head>
<title>unpkg-demos :: global-react</title>
</head>
<body>
<div id="app"></div>
<script src="https://unpkg.com/react@16.0.0-beta.2/umd/react.production.min.js"
integrity="sha384-lJJbYsDe7wDuOttI/MIHfj68o3fVZOhJDxEn0cTPbDq5mkzjF1p+AFEp3r/HpUnt"
crossorigin="anonymous"></script>
<script src="https://unpkg.com/react-dom@16.0.0-beta.2/umd/react-dom.production.min.js"
integrity="sha384-urrH8a5NtX87DSmFO4pKPICl5RHszNM6yx75JIYhynT2ukWDK4skf0YAh4EDEdD2"
crossorigin="anonymous"></script>
<script src="https://unpkg.com/babel-standalone@6.24.2/babel.min.js" charset="utf-8"></script>
<script src="https://unpkg.com/redux@3.7.2/dist/redux.min.js"></script>
<script src="https://unpkg.com/react-redux@5.0.6/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