Created
June 1, 2025 14:58
-
-
Save rusintez/1993b9e928ffe7ba353c9e9a17f46a83 to your computer and use it in GitHub Desktop.
zero-deps-react
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
| <div id="root"></div> | |
| <script> | |
| /** | |
| * Poorman's jQuery | |
| */ | |
| const $ = document.querySelector.bind(document); | |
| /** | |
| * Poorman's jsx | |
| */ | |
| function h(element, props = {}, children = []) { | |
| if (typeof element === "string") { | |
| const el = document.createElement(element); | |
| Object.entries(props).forEach(([key, value]) => { | |
| if (key.startsWith("on")) el[key] = value; | |
| else el.setAttribute(key, value); | |
| }); | |
| [].concat(children).forEach((child) => { | |
| if (child instanceof HTMLElement) el.appendChild(child); | |
| else el.innerText = child; | |
| }); | |
| return el; | |
| } else { | |
| return element({ ...props, children }); | |
| } | |
| } | |
| /** | |
| * Poorman's Observable | |
| */ | |
| const wrap = (render) => | |
| function _wrap(obj) { | |
| return new Proxy(obj, { | |
| set(target, prop, value) { | |
| Reflect.set(target, prop, value); | |
| render(); | |
| }, | |
| get(target, prop) { | |
| const value = Reflect.get(target, prop); | |
| if ( | |
| value && | |
| typeof value === "object" && | |
| ["Array", "Object"].includes(value.constructor.name) | |
| ) | |
| return _wrap(value); | |
| return value; | |
| }, | |
| }); | |
| }; | |
| /** | |
| * Poorman's React | |
| */ | |
| const render = (root, comp, initialState = {}) => { | |
| const _render = () => root.replaceChildren(comp(state)); | |
| const state = wrap(_render)(initialState); | |
| _render(); | |
| }; | |
| /** | |
| * Full Demo | |
| */ | |
| render( | |
| $("#root"), | |
| (state) => { | |
| const Container = ({ children }) => h("div", {}, children); | |
| const Comp = () => | |
| h("div", {}, [ | |
| h("p", { style: `color: ${state.counter > 3 ? "red" : "green"};` }, [ | |
| `Counter is: ${state.counter}`, | |
| ]), | |
| h("button", { onclick: () => state.counter++ }, ["Increment"]), | |
| ]); | |
| return h(Container, {}, [h(Comp)]); | |
| }, | |
| { counter: 0 } | |
| ); | |
| </script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment