Skip to content

Instantly share code, notes, and snippets.

@sergey-shpak
Created January 3, 2019 23:54
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 sergey-shpak/a1bf7e88affa469353ffa27ccfbb9689 to your computer and use it in GitHub Desktop.
Save sergey-shpak/a1bf7e88affa469353ffa27ccfbb9689 to your computer and use it in GitHub Desktop.
Hyperapp#v2 Context Implementation
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
}
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