Created
June 16, 2018 01:43
-
-
Save ronit-mukherjee/63a85c5113f8a3ce5a9cb5de3025f275 to your computer and use it in GitHub Desktop.
index.js file of create-react-app to display list of products in React, show bought quantities, show total amount and show individual products
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
/* | |
* Author:- Ronit Mukherjee | |
* Email:- connect.ronit@gmail.com | |
* Website:- ronitmukherjee.com | |
* CreatedOn:- 16-06-2018 7:12 AM | |
*/ | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
class ProductList extends React.Component{ | |
constructor(props){ | |
super(props); | |
this.state = {total: 0} | |
} | |
calculateTotal(price){ | |
this.setState(prevState => ( | |
{ | |
total: parseInt(prevState.total,10) + parseInt(price,10) | |
} | |
),()=>{//callback fuction | |
console.log(this.state.total); | |
}); | |
} | |
showProduct(name){ | |
alert("You Selected " + name); | |
} | |
render(){ | |
return( | |
<div> | |
<Product | |
name="Samsung" | |
price="100" | |
handelShow={name => this.showProduct(name)} | |
handelTotal={price => this.calculateTotal(price)} | |
/> | |
<Product | |
name="Nokia" | |
price="150" | |
handelShow={name => this.showProduct(name)} | |
handelTotal={price => this.calculateTotal(price)} | |
/> | |
<Product | |
name="Apple" | |
price="200" | |
handelShow={name => this.showProduct(name)} | |
handelTotal={price => this.calculateTotal(price)} | |
/> | |
<Total total={this.state.total} /> | |
</div> | |
) | |
} | |
} | |
class Product extends React.Component{ | |
constructor(props){ | |
super(props); | |
this.state = {qty: 0} | |
} | |
buy(){ | |
this.setState(prevState => { | |
return ({qty: prevState.qty +1}) | |
}); | |
this.props.handelTotal(this.props.price); | |
} | |
show(){ | |
this.props.handelShow(this.props.name); | |
} | |
render(){ | |
return( | |
<div> | |
<h2> {this.props.name}</h2> | |
<h3> Price - ${this.props.price}</h3> | |
<h4>Qty - {this.state.qty}</h4> | |
<button onClick={this.buy.bind(this)}>Buy Now</button> | |
<button onClick={this.show.bind(this)}>Show</button> | |
<hr/> | |
</div> | |
) | |
} | |
} | |
class Total extends React.Component{ | |
render(){ | |
return( | |
<div> | |
<h4> Total Cash : {this.props.total} </h4> | |
</div> | |
) | |
} | |
} | |
ReactDOM.render( | |
<ProductList />, | |
document.getElementById("root") | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment