React | Ex2
let isLoggedIn=true;
// isLoggedIn=false;
let username = "Chandan";
class UserStatus extends React.Component {
render() {
return (
<div>
<button>Login</button>
<h2> Hey, {username}!</h2>
</div>
)
}
}
ReactDOM.render(
<UserStatus />,
document.getElementById('root')
);
------------------------------------------------------------------------------------------------
State and event handling
------------------------------------------------------------------------------------------------
class LikeCounter extends React.Component {
state = {
counter : 0
}
likeButtonHandler = () => {
this.setState({ counter: this.state.counter + 1 });
}
render() {
console.log('render function is being called with state', this.state.counter);
return (
<div>
<button onClick={this.likeButtonHandler}> ❤️ </button>
<h2> Likes {this.state.counter} </h2>
</div>
)
}
}
ReactDOM.render(
<LikeCounter />,
document.getElementById('root')
);
----------------------------------------------------------------------------------------------------------------------
sugar cart state handling
----------------------------------------------------------------------------------------------------------------------
class Cart extends React.Component {
state = {
cartCounter : 0
}
addToCart = () => {
this.setState({ cartCounter: this.state.cartCounter + 1 });
console.log('add console');
console.log(this.state.cartCounter);
}
removeFromcart = () => {
this.setState({ cartCounter: this.state.cartCounter - 1 });
console.log('remove console');
console.log(this.state.cartCounter);
if(this.state.cartCounter<2){
console.log('Empty Cart');
}
}
render() {
return (
<div>
<h1>Sugar</h1>
<button onClick={this.addToCart}> Add to Cart </button>
<button onClick={this.removeFromcart}> Remove from Cart </button>
<h2>Cart Status: {this.state.cartCounter}</h2>
</div>
)
}
}
ReactDOM.render(
<Cart />,
document.getElementById('root')
);
Comments
Post a Comment