-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathGroceryApp.js
63 lines (54 loc) · 1.54 KB
/
GroceryApp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import React from 'react';
import { createRoot } from 'react-dom/client';
const Product = props => {
const { name, votes } = props.product;
const plus = () => {
// Call props.onVote to increase the vote count for this product
props.onVote(1,props.index);
};
const minus = () => {
// Call props.onVote to decrease the vote count for this product
props.onVote(-1,props.index);
};
return (
<li>
<span>{name}</span> - <span>votes: {votes}</span>
<button onClick={plus}>+</button>{" "}
<button onClick={minus}>-</button>
</li>
);
};
const GroceryApp = (props) => {
let [products, setProducts] = React.useState(props.products);
const onVote = (dir, index) => {
setProducts((prevProducts) => {
const updatedProducts = [...prevProducts];
updatedProducts[index] = { ...updatedProducts[index], votes: updatedProducts[index].votes + dir };
return updatedProducts;
});
};
return (
<ul>
{products.map((product,index) => (
<Product key={index} product={product} index={index} onVote={onVote} />
))}
</ul>
);
}
document.body.innerHTML = "<div id='root'></div>";
const root = createRoot(document.getElementById("root"));
root.render(<GroceryApp
products={[
{ name: "Oranges", votes: 0 },
{ name: "Bananas", votes: 0 }
]}
/>);
setTimeout(() => {
let plusButton = document.querySelector("ul > li > button");
if(plusButton) {
plusButton.click();
}
setTimeout(() => {
console.log(document.getElementById('root').outerHTML);
});
});