JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdn.jsdelivr.net/npm/barleytea@latest/public/barleytea.js"></script>
<todo-list></todo-list>
JavaScript
class TodoList extends HTMLElement {
state = {
todos: ['write tests', 'debug code']
}
// this makes it possible to quickly add a todo on an "Enter" keypress
handleKeyDown = e => {
if (e.key === 'Enter' && e.target.value) {
e.preventDefault()
this.addTodo(e.target.value)
e.target.value = ''
}
}
// add a new todo with the given string value
addTodo = todo => {
this.state.todos = [...this.state.todos, todo]
}
// remove a todo by index
removeTodo = idx => {
this.state.todos = [...this.state.todos.slice(0, idx), ...this.state.todos.slice(idx + 1)]
}
render({ html, keyed, state }) {
return html`
<div>
<h1>To dos:</h1>
<input
placeholder='Enter a new item here'
.onkeydown=${this.handleKeyDown}>
<button
.onclick=${this.addTodo}>Add</button>
<ul>
${state.todos.map((todo, idx) => keyed(idx)`
<li>
${todo}
<button
.onclick=${() => this.removeTodo(idx)}>X</button>
</li>`
)}
</ul>
</div>
`
}
}
define('todo-list', TodoList)