Created
December 7, 2020 14:06
-
-
Save nirkaufman/fb6079d57f088275d57c0174fe413e53 to your computer and use it in GitHub Desktop.
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
| function renderElement(element) { | |
| const {type, props, children} = element; | |
| // component support | |
| if(typeof type === 'function') { | |
| return renderElement(type(props)); | |
| } | |
| const domElement = document.createElement(type); | |
| // child support | |
| children.forEach( child => { | |
| let node = null; | |
| if(typeof child === 'string') { | |
| node = document.createTextNode(child); | |
| } else { | |
| node = renderElement(child); | |
| } | |
| domElement.appendChild(node); | |
| }); | |
| // support props | |
| Object.keys(props).forEach( key => { | |
| if(key.startsWith('on')) { | |
| const eventName = key.slice(2).toLowerCase(); | |
| domElement.addEventListener(eventName, props[key]) | |
| } | |
| }) | |
| return domElement; | |
| } | |
| export function render(element, container) { | |
| const app = renderElement(element); | |
| container.appendChild(app); | |
| } |
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 {createElement as e} from './reakt.js'; | |
| import {render} from './reakt-dom.js'; | |
| const App = e('div', {}, | |
| e('h1', {}, 'React IO'), | |
| e(Counter), | |
| ) | |
| function Counter() { | |
| return e('div', {}, | |
| e('h2', {}, '0'), | |
| e(Button, {label: '+', onClick: () => console.log('click +')}, []), | |
| e(Button, {label: '-', onClick: () => console.log('click -')}, []), | |
| ) | |
| } | |
| function Button({label, onClick}) { | |
| return e('button', {onClick: onClick}, label); | |
| } | |
| render(App, document.getElementById('app')); | |
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
| export function createElement(type, props, ...children) { | |
| const element = {type, props, children}; | |
| Object.freeze(element) | |
| Object.freeze(element.props) | |
| return element; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment