Created
April 12, 2018 18:15
-
-
Save danawoodman/030f4e10ea2e566f1d6767c68b320212 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react"; | |
function ProductItem({ product }) { | |
return ( | |
<li> | |
{product.name} {product.price} | |
</li> | |
); | |
} | |
class AddProduct extends React.Component { | |
constructor(props) { | |
super(props); | |
this.input = React.createRef(); | |
this.state = { error: null }; | |
} | |
handleSubmit = e => { | |
e.preventDefault(); | |
// Clear error messages | |
this.setState({ error: null }); | |
// Validate the product name | |
const name = this.input.current.value; | |
if (name === "bonafide") { | |
this.setState({ error: "Cant call this Bonafide!" }); | |
return; | |
} | |
// Add the product | |
this.props.addProduct({ name, price: 100 }); | |
this.input.current.value = ""; | |
}; | |
render() { | |
const { error } = this.state; | |
return ( | |
<form onSubmit={this.handleSubmit}> | |
{error && <strong>{error}</strong>} | |
<input type="text" ref={this.input} autoFocus /> | |
<button>Add product</button> | |
</form> | |
); | |
} | |
} | |
function ProductList({ addProduct, products }) { | |
return ( | |
<div> | |
<ul> | |
{products.map((product, key) => ( | |
<ProductItem product={product} key={key} /> | |
))} | |
</ul> | |
<AddProduct addProduct={addProduct} /> | |
</div> | |
); | |
} | |
class App extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
products: [ | |
{ name: "iPhone X", price: 10000000 }, | |
{ name: "Android", price: 20 } | |
] | |
}; | |
} | |
addProduct = product => { | |
this.setState({ | |
products: [...this.state.products, product] | |
}); | |
}; | |
render() { | |
// const { products } = this.state; | |
return ( | |
<ProductList | |
products={this.state.products} | |
addProduct={this.addProduct} | |
/> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment