Skip to content

Instantly share code, notes, and snippets.

@edwilliams
Created April 3, 2024 06:52
Show Gist options
  • Select an option

  • Save edwilliams/89601fa8e790f55ff13cb738ed7db3bf to your computer and use it in GitHub Desktop.

Select an option

Save edwilliams/89601fa8e790f55ff13cb738ed7db3bf to your computer and use it in GitHub Desktop.
Minimal no-framework reducer example
import { Main } from "./templates/main.mjs"
let state = { counter: 0 }
const render = () => (document.body.innerHTML = Main({ state }))
const reducer = (e) => {
const { action } = e.target.dataset
const actions = {
increment: () => {
state.counter = state.counter + 1
},
decrement: () => {
state.counter = state.counter - 1
},
}
actions[action]()
render()
}
// single listener for all clicks
document.addEventListener("click", reducer)
render()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>No Framework</title>
</head>
<body>
<script type="module" src="app.mjs"></script>
</body>
</html>
import { html } from "../utils.mjs"
export const Main = ({ state }) => {
return html`<div>
<p>
<span>Counter</span>
<span>${state.counter}</span>
</p>
<button data-action="increment">Increment</button>
<button data-action="decrement">Decrement</button>
</div>`
}
/**
* Template tag to convert HTML into a string
* For syntax highlighting only
* @param {string[]} strings
* @param {...*} keys
* @returns {string}
*/
export function html(strings, ...keys) {
return strings.flatMap((string, i) => [string, keys[i]]).join("")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment