JSFiddle - React, Tailwind, and code Playground
by brigand
JavaScript
const create = (tag, props, ...children) => {
const element = document.createElement(tag);
Object.assign(element, props);
for (const child of children) {
element.appendChild(child);
}
return element;
}
const on = (element, event, handler) => {
element.addEventListener(event, handler, false);
}
const remove = (element) => {
element.parentElement.removeChild(element);
}
function makeItem(data) {
const yes = create('button', {
textContent: 'Yes',
type: 'button'
});
const no = create('button', {
textContent: 'No',
type: 'button'
});
const label = create('div', {
textContent: 'Make a choice:'
});
const log = create('pre');
const answer = (action) => {
const nextData = {
yes: action === 'yes' ? data.yes + 1 : data.yes,
no: action === 'no' ? data.no + 1 : data.no,
};
log.textContent = `You selected ${action}. Presses:\nYes: ${nextData.yes}\nNo: ${nextData.no}`;
remove(label);
remove(yes)
remove(no);
document.body.appendChild(makeItem(nextData));
}
on(yes, 'click', (event) => {
answer('yes')
});
on(no, 'click', (event) => {
answer('no')
});
return create('div', {}, label, yes, no, log);
}
document.body.appendChild(makeItem({
yes: 0,
no: 0
}))