Created
April 3, 2024 06:52
-
-
Save edwilliams/89601fa8e790f55ff13cb738ed7db3bf to your computer and use it in GitHub Desktop.
Minimal no-framework reducer example
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
| 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() |
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
| <!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> |
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
| 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>` | |
| } |
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
| /** | |
| * 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