Skip to content

Instantly share code, notes, and snippets.

@nirkaufman
Created December 7, 2020 14:06
Show Gist options
  • Select an option

  • Save nirkaufman/fb6079d57f088275d57c0174fe413e53 to your computer and use it in GitHub Desktop.

Select an option

Save nirkaufman/fb6079d57f088275d57c0174fe413e53 to your computer and use it in GitHub Desktop.
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);
}
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'));
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