React - Array Update - Test
by syjsdev
React
const Product = props => {
const plus = () => {
// Call props.onVote to increase the vote count for this product
props.onVote(props.dir, props.votes + 1);
};
const minus = () => {
// Call props.onVote to decrease the vote count for this product
props.onVote(props.dir, props.votes - 1);
};
return (
<li>
<span>{/* Product name */props.name}</span> - <span>votes: {/* Number of votes*/props.votes}</span>
<button onClick={plus}>+</button>{" "}
<button onClick={minus}>-</button>
</li>
);
};
class GroceryApp extends React.Component {
// Finish writing the GroceryApp class
constructor(props) {
super(props)
this.state = {
products: props.products,
}
}
onVote = (dir, index) => {
// Update the products array accordingly ...
this.setState({ products: this.state.products.map((item, i) => dir === i ? { ...item, votes: index } : item) });
};
render() {
return (
<ul>
{/* Render an array of products, which should call this.onVote when + or - is clicked */
this.state.products.map((prod, i) => (<Product key={i} {...prod} dir={i} onVote={this.onVote} />))
}
</ul>
);
}
}
document.body.innerHTML = "<div id='root'></div>";
ReactDOM.render(<GroceryApp
products={[
{ name: "Oranges", votes: 0 },
{ name: "Bananas", votes: 0 }
]}
/>, document.getElementById('root'));
console.log(document.getElementById('root').innerHTML)