Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save gyopiazza/7e3e9e28e1199b560ef5a6641298eb80 to your computer and use it in GitHub Desktop.

Select an option

Save gyopiazza/7e3e9e28e1199b560ef5a6641298eb80 to your computer and use it in GitHub Desktop.

Revisions

  1. @sergey-shpak sergey-shpak renamed this gist Dec 28, 2018. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. @sergey-shpak sergey-shpak created this gist Dec 28, 2018.
    55 changes: 55 additions & 0 deletions example.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,55 @@
    import { app, h } from "hyperapp";
    import { Stateful } from './helpers'

    /* Working example, https://codepen.io/sergey-shpak/pen/maMopd */

    // --- STATEFUL COMPONENT ---

    // Don't use arrow functions for stateful components/actions
    // Since context is linked to it's definition context

    // Don't forget to return new state to trigger view re-render

    // You can get local component state as function context (this)
    // In all other senses it is a typical component. Enjoy!

    function onFocus(state){
    this.focused = true
    return { ...state }
    }

    function onBlur(state){
    this.focused = false
    return { ...state }
    }

    function Input(props, children){
    return [
    h('input', {
    onFocus: onFocus.bind(this),
    onBlur: onBlur.bind(this)
    }),
    h('div', {}, `Focused ${this.focused}`)
    ]
    }

    // Exposing initial component state
    Input.state = { focused: false }

    // --- USAGE EXAMPLE ---

    // Init stateful component (with default state)
    const InputBox1 = Stateful(Input)
    // or you can override initial component state
    const InputBox2 = Stateful(Input, {
    focused: true
    })

    app({
    init: {},
    view: () => h('div', {}, [
    h(InputBox1, {}),
    h(InputBox2, {}),
    ]),
    container: document.body
    })
    11 changes: 11 additions & 0 deletions stateful.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,11 @@
    /*
    This is implementation of Hyperapp#v2 stateful components
    Helpful when you don't want to expose internal component state
    or you want to create a simple and re-usable component
    */

    export const Stateful = (Component, state) =>
    Component.bind(state || Component.state || {})