Skip to content

Instantly share code, notes, and snippets.

@javedbaloch4
Created January 29, 2019 16:32
Show Gist options
  • Save javedbaloch4/4998ab7e329d1f532c957574c7f76f49 to your computer and use it in GitHub Desktop.
Save javedbaloch4/4998ab7e329d1f532c957574c7f76f49 to your computer and use it in GitHub Desktop.
Simple React Counter App with State full component.
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>&nbsp;
<button onClick={this.subOne}>-1</button>&nbsp;
<button onClick={this.reset}>Reset</button>&nbsp;
<button onClick={this.cube}>Cube</button>&nbsp;
<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