Created
January 3, 2019 23:54
-
-
Save sergey-shpak/a1bf7e88affa469353ffa27ccfbb9689 to your computer and use it in GitHub Desktop.
Hyperapp#v2 Context Implementation
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 { h } from 'hyperapp' | |
/* | |
This is implementation of Hyperapp#v2 Context | |
Helpful when you want to pass properties to internal components | |
without multiple components compositions | |
*/ | |
export const Context = ({ tag }, childs) => | |
ctx( tag || 'main', {}, childs ) | |
export const ctx = (node, props, ...fns) => { | |
const roll = context => { | |
const childs = fns.map(fn => | |
typeof fn === 'function' ? fn(context) : fn) | |
return typeof node === 'function' | |
? node({ ...props, context }, childs)(context) | |
: h( node, props, ...childs ) | |
} | |
return node === Context ? roll(props) : roll | |
} |
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 { ctx, Context } from './context' | |
/* Working example, https://codepen.io/sergey-shpak/pen/Ydeamj */ | |
// IMPORTANT | |
// You have to change transform-react-jsx pragma to 'ctx' | |
// And import 'ctx' from helpers, as you usually do with 'h' | |
const Component = (props, childs) => | |
<div>This is { props.context.name } context</div> | |
app({ | |
init: {}, | |
view: state => | |
// Defined <Context> properties are passed down to each <Component> | |
// and can be accessable as 'props.context.propname' from Component | |
// You can pass any property, state, etc | |
// IMPORTANT | |
// Any application which is using Context | |
// Should have Context as root app component | |
<Context state={ state } name='Top level'> | |
<header> | |
<Component /> | |
</header> | |
<Context name='Second level'> | |
<div> | |
<Component prop='some' /> | |
</div> | |
</Context> | |
</Context>, | |
container: document.body | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment