React Base Fiddle (JSX)
Starting point for creating JSFiddles with React.
HTML
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root">
<!-- This element's contents will be replaced with your component. -->
</div>
Babel + JSX
const Product = props => {
const plus = () => {
// Call props.onVote to increase the vote count for this product
props.onVote(true, props.index)
};
const minus = () => {
// Call props.onVote to decrease the vote count for this product
props.onVote(false, props.index)
};
return (
<li>
<span>{props.product.name}</span> - <span>votes: {props.product.votes}</span>
<button onClick={plus}>+</button>{" "}
<button onClick={minus}>-</button>
</li>
);
};
class GroceryApp extends React.Component {
// Finish writing the GroceryApp class
state = {
products: this.props.products
}
onVote = (dir, index) => {
// Update the products array accordingly ...
console.log(this.state)
/*let products = [
...this.state.products,
[index]: {...this.state.products[index],
votes: 100
}
];*/
let products = [...this.state.products] // clone the array
products[index].votes = dir ? products[index].votes + 1 : products[index].votes - 1
// products[index].votes = dir ? products[index].votes + 1 : products[index].votes - 1
/*const updated = [
...oldArray,
oldArray[index]: { ...oldArray[index]
votes: dir? oldArray[index].votes++ : oldArray[index].votes-- // attributes to change...
}
] */
console.log(this.state.products[index].votes)
// this.setState({products})
};
render() {
let { products } = this.state
return (
<ul>
{/* Render an array of products, which should call this.onVote when + or - is clicked */
products.map((product, index) =>
(<Product
key={index}
index={index}
product={product}
onVote={this.onVote}
/>)
)
}
</ul>
);
}
}
document.body.innerHTML = "<div id='root'></div>";
ReactDOM.render(<GroceryApp
products={[
{ name: "Oranges", votes: 0 },
{ name: "Apples", votes: 0 },
{ name: "Bananas",...