Todo Example

Riot custom components are the building blocks for user interfaces. They make the “view” part of the application. Let’s start with an extended <todo> example highlighting various features of Riot:

  1. <todo>
  2. <h3>{ props.title }</h3>
  3. <ul>
  4. <li each={ item in state.items }>
  5. <label class={ item.done ? 'completed' : null }>
  6. <input
  7. type="checkbox"
  8. checked={ item.done }
  9. onclick={ () => toggle(item) } />
  10. { item.title }
  11. </label>
  12. </li>
  13. </ul>
  14. <form onsubmit={ add }>
  15. <input onkeyup={ edit } value={ state.text } />
  16. <button disabled={ !state.text }>
  17. Add #{ state.items.length + 1 }
  18. </button>
  19. </form>
  20. <script>
  21. export default {
  22. onBeforeMount(props, state) {
  23. // initial state
  24. this.state = {
  25. items: props.items,
  26. text: ''
  27. }
  28. },
  29. edit(e) {
  30. // update only the text state
  31. this.update({
  32. text: e.target.value
  33. })
  34. },
  35. add(e) {
  36. e.preventDefault()
  37. if (this.state.text) {
  38. this.update({
  39. items: [
  40. ...this.state.items,
  41. // add a new item
  42. {title: this.state.text}
  43. ],
  44. text: ''
  45. })
  46. }
  47. },
  48. toggle(item) {
  49. item.done = !item.done
  50. // trigger a component update
  51. this.update()
  52. }
  53. }
  54. </script>
  55. </todo>

Custom components are compiled to javascript.

See the live demo, browse the sources, or download the zip.