React
HTML
<div id="app"></div>
CSS
html,
body {
margin: 0;
height: 100%;
}
body {
background-color: #ffffff;
font-family: Helvetica, Arial, sans-serif;
text-align: center;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
input {
margin-right: 5px;
}
.tablewrapper {
display: flex;
justify-content: center;
flex-direction: column;
margin: 10px;
}
.flextable {
padding: 4px;
display: flex;
flex-direction: row;
justify-content: center;
}
.row {
padding: 2px;
}
form {
display: flex;
justify-content: center;
flex-direction: row;
margin-bottom: 15px;
}
React
const {useEffect, useState, useRef} = React;
function App() {
const [items, setItems] = useState([
{item: "bacon", count: 0},
{item: "cheese", count: 0}
]);
const [purchasble, setPurchasble] = useState(false);
const [inputValue, setInputValue] = useState('');
useEffect(() => {
let totalCount = 0;
items.forEach((item) => {
totalCount = totalCount + item.count
})
if(totalCount > 0)
setPurchasble(true)
else
setPurchasble(false)
},[items])
const handleSubmit = (event) => {
event.preventDefault();
const newItem = {
item: inputValue,
count: 1
}
setItems([...items, newItem])
setInputValue('')
}
const handleChange = (event) => {
setInputValue( event.target.value)
}
const addCount = (index) => {
const old = items[index]
const updated = {...old, count: old.count + 1}
const clone = [...items]
clone[index] = updated
setItems(clone)
}
const removeCount = (index) => {
const old = items[index]
const updated = {...old, count: old.count > 0 ? old.count - 1 : 0}
const clone = [...items]
clone[index] = updated
setItems(clone)
}
const removeItem = (index) => {
const clone = [...items]
clone.splice(index, 1)
setItems(clone)
}
return (
<div>
<form onSubmit={handleSubmit}>
<label>
Item:
<input type="text" value={inputValue} onChange={handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
<div className="tablewrapper">
{items.map((item, index) => (
<div key={Math.random()} className="flextable">
<div className="row">{item.item}</div>
<div className="row">{item.count}</div>
<button onClick={() => addCount(index)}>+</button>
<button onClick={() => removeCount(index)}>-</button>
<button onClick={() => removeItem(index)}>Remove</button>
</div>
...