Created
January 29, 2019 16:32
-
-
Save javedbaloch4/4998ab7e329d1f532c957574c7f76f49 to your computer and use it in GitHub Desktop.
Simple React Counter App with State full component.
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 from 'react'; | |
const container = { width: '1000px', margin: '20px auto'} | |
class App extends React.Component { | |
constructor(props) { | |
super(props); | |
this.addOne = this.addOne.bind(this); | |
this.subOne = this.subOne.bind(this); | |
this.reset = this.reset.bind(this); | |
this.cube = this.cube.bind(this); | |
this.square = this.square.bind(this); | |
this.state = { | |
count: 0, | |
} | |
} | |
addOne() { | |
this.setState((prevState) => { | |
return { | |
count: prevState.count + 1 | |
} | |
}); | |
} | |
subOne() { | |
this.setState((prevState) => { | |
return { | |
count: prevState.count -1 | |
} | |
}); | |
} | |
reset() { | |
this.setState(() => { | |
return { | |
count: 0 | |
} | |
}); | |
} | |
cube() { | |
this.setState((prevState) => { | |
if (prevState.count > 0) { | |
return { | |
count: prevState.count * 3 | |
} | |
} else { | |
alert('Please increment by 1') | |
} | |
}); | |
} | |
square() { | |
this.setState((prevState) => { | |
if (prevState.count > 0) { | |
return { | |
count: prevState.count * 2 | |
} | |
} else { | |
alert('At least increment with 1 to get square') | |
} | |
}) | |
} | |
render() { | |
return ( | |
<div style={container}> | |
<h1>Count: {this.state.count}</h1> | |
<button onClick={this.addOne}>+1</button> | |
<button onClick={this.subOne}>-1</button> | |
<button onClick={this.reset}>Reset</button> | |
<button onClick={this.cube}>Cube</button> | |
<button onClick={this.square}>Square</button> | |
</div> | |
) | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment