Skip to content

Instantly share code, notes, and snippets.

@jongacnik
Last active November 25, 2017 05:05
Show Gist options
  • Save jongacnik/01daeea0b216632edf3f0e27b8f0b89a to your computer and use it in GitHub Desktop.
Save jongacnik/01daeea0b216632edf3f0e27b8f0b89a to your computer and use it in GitHub Desktop.
choop - nanocomponent
var choop = require('choop')
var html = require('choop/html')
var h = require('choop/h')
var preact = require('preact')
var devtools = require('choo-devtools')
var Nanocomponent = require('nanocomponent')
var bel = require('bel')
var app = choop()
app.use(devtools())
app.route('*', mainView)
app.mount('body')
class ClickMe extends Nanocomponent {
constructor () {
super()
this.count = 0
this.handleClick = () => {
this.count++
this.rerender()
}
}
createElement () {
return bel`
<div>
<h1>clicked ${this.count} times</h1>
<button onclick=${this.handleClick}>click me!</button>
</div>
`
}
}
var PreactClickMe = toReact(ClickMe, preact)
function mainView (state, emit) {
return html`
<main>
${h(PreactClickMe)}
${h(PreactClickMe)}
${h(PreactClickMe)}
</main>
`
}
/**
* Will be merged into nanocomponent-adapters soon
* https://github.com/choojs/nanocomponent-adapters
*/
function toReact (Component, react) {
return class Clx extends react.Component {
constructor () {
super()
this.comp = new Component()
this.node = null
this.setRef = this.setRef.bind(this)
}
componentDidMount () {
if (!this.comp.element) {
var el = this.comp.render(this.props)
this.node.appendChild(el)
}
}
setRef (_node) {
this.node = _node
}
componentWillReceiveProps (props) {
if (this.comp.element) this.comp.render(props)
}
shouldComponentUpdate () {
return false
}
render (props) {
return react.createElement('div', { ref: this.setRef })
}
}
}
{
"dependencies": {
"bel": "5.1.5",
"choop": "3.0.0",
"choo-devtools": "2.2.0",
"nanocomponent": "6.4.2",
"preact": "8.2.6"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment