-
-
Save ashnur/69c6a6b59e052a5a4f307689b7a4d5a2 to your computer and use it in GitHub Desktop.
Web Components, the React way, without Shadow DOM
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 characters
// https://hackernoon.com/web-components-the-react-way-8ed5b6f4f942#.5em3zpgin | |
const store = (() => { | |
let state; | |
return todos => { | |
if (todos) { | |
state = todos; | |
render("todo-list"); | |
} | |
return state; | |
}; | |
})(); | |
const render = (component, parent = document.body) => | |
parent.innerHTML = `<${component}></${component}>`; | |
customElements.define("todo-item", class extends HTMLElement { | |
static get observedAttributes() { | |
return ["index"]; | |
} | |
attributeChangedCallback(name, old, change) { | |
this.index = change; | |
} | |
connectedCallback() { | |
this.innerHTML = ` | |
<label> | |
<input type=checkbox> | |
${this.innerHTML} | |
</label> | |
`; | |
this.querySelector("input").addEventListener("click", () => | |
store(store().filter((todo, index) => index != this.index))); | |
} | |
}); | |
customElements.define("todo-list", class extends HTMLElement { | |
connectedCallback() { | |
this.innerHTML = ` | |
<ul> | |
${store().map((todo, index) => ` | |
<li> | |
<todo-item index=${index}> | |
${todo} | |
</todo-item> | |
</li> | |
`).join("")} | |
</ul> | |
`; | |
} | |
}); | |
store(["Buy milk", "Call Sarah", "Pay bills"]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment