Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Forked from bloodyowl/Component.js
Created January 4, 2017 15:35
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 tomhodgins/8d78fd1d0cb2a3a6bbe1dcb113408fce to your computer and use it in GitHub Desktop.
Save tomhodgins/8d78fd1d0cb2a3a6bbe1dcb113408fce to your computer and use it in GitHub Desktop.
Component library in less than 140 bytes
b=0;$=x=>(p,i="_"+b++,u=($[i]=q=>eval(i).innerHTML=x(p,$[q],u),z=>($[++b]=z,`$.${i}(${b})`)))=>`<c id=${i}>${x(p,[]._,u)}</c>`
b = 0; // global ID
$ = // component
x => // render function
(
p, // props
i = "_" + b++, // id
u = (
// updater = nextStateID => document.getElementById(id).innerHTML = render(props, states[nextStateID], update)
$[i] = q => eval(i).innerHTML = x(p, $[q], u),
// nextState => { id = nuid(); states[id] = nextState; return () => updater(id) }
z => (
$[++b] = z,
`$.${i}(${ b })`
)
)
// return the contents
) => `<c id=${i}>${ x(p, []._, u) }</c>`
// Test at https://jsfiddle.net/bloodyowl/hkpbtmbo/
const DecrementButton = $(props =>
`<div>
<button onclick="${ props.decrement }">decrement</button>
</div>`
)
const IncrementButton = $(props =>
`<div>
<button onclick="${ props.increment }">increment</button>
</div>`
)
const App = $((props, state = 0, update) =>
`<div>
<b>${ state }</b>
${ IncrementButton({ increment: update(state + 1) }) }
${ state === 0 ? `` : DecrementButton({ decrement: update(state - 1) }) }
</div>`
)
document.body.innerHTML = App({})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment