Forked from sergey-shpak/hyperapp-stateful-component-example.js
Created
September 18, 2019 09:00
-
-
Save gyopiazza/7e3e9e28e1199b560ef5a6641298eb80 to your computer and use it in GitHub Desktop.
Revisions
-
sergey-shpak renamed this gist
Dec 28, 2018 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
sergey-shpak created this gist
Dec 28, 2018 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal 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 }) This file contains hidden or 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 charactersOriginal 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 || {})