JSFiddle - React, Tailwind, and code Playground
by Marco Abate
HTML
<section class='container'>
<input type='text' id='input' placeholder='Type in value...' />
<div class='buttonContainer'>
<button id='button' type='button'>Reset</button>
</div>
<div class='box' id='firstBox'></div>
<div class='box' id='secondBox'></div>
</section>
CSS
* { box-sizing: border-box; }
.container {
padding: 1rem;
}
body {
font-family: sans-serif;
}
input {
margin-bottom: 1rem;
font-size: 1rem;
padding: 0.4em;
width: 100%;
outline: none;
border-radius: 0.5rem;
border: 0.125rem solid teal;
}
.buttonContainer {
margin-bottom: 1rem;
text-align: right;
}
.buttonContainer button {
background-color: teal;
color: white;
outline: none;
font-size: 1rem;
padding: 0.5rem 1rem;
cursor: pointer;
border-radius: 0.25rem;
border: none;
border-bottom: 0.125rem solid black;
}
.buttonContainer button:active {
background-color: #014f4f;
}
.box {
padding: 1rem;
margin-bottom: 1rem;
border: 1px solid teal;
text-align: center;
}
JavaScript
const initialState = {
firstBox: 'Box 1',
secondBox: 'Box 2'
}
let handler = {
get: function(target, key) {
if(target && target[key]) return target[key];
return '';
},
set: function(obj, prop, nextVal) {
let oldValue = obj[prop];
if(oldValue !== nextVal) {
obj[prop] = nextVal;
triggerDomReaction();
}
return true;
}
};
let state = new Proxy({}, handler);
const getReferences = () => {
const firstBox = document.querySelector('#firstBox');
const secondBox = document.querySelector('#secondBox');
return { firstBox, secondBox }
}
const triggerDomReaction = () => {
const refs = getReferences();
if(refs.firstBox) firstBox.innerText = state.firstBox;
if(refs.secondBox) secondBox.innerText = state.secondBox;
}
Object.keys(initialState).forEach(e => {
state[e] = initialState[e]
})
const input = document.querySelector('#input');
const button = document.querySelector('#button');
input.oninput = e => {
state.firstBox = e.target.value;
}
button.onclick = () => {
state.secondBox = state.firstBox;
state.firstBox = '';
}