Skip to content

Instantly share code, notes, and snippets.

@azamsharp
Created June 9, 2020 15:03
Show Gist options
  • Save azamsharp/79ed6b3582577380c1d5d00add82191e to your computer and use it in GitHub Desktop.
Save azamsharp/79ed6b3582577380c1d5d00add82191e to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import './App.css';
import Counter from './components/Counter'
class App extends Component {
constructor() {
super() // calls the constructor of the Component
console.log(this) // this is App component and it is DEFINED
// State is just an object which can have property and values
this.state = {
counter: 0
}
//this.counter = 0 // property called counter
// Inside the constructor this is defined and use the value of this from inside the constructor in the body of the handleIncrement function
//this.handleIncrement = this.handleIncrement.bind(this)
}
handleIncrement = () => {
this.setState({
counter: this.state.counter + 1
})
}
// handleIncrement function must be bind in order to access the value of this
handleIncrement() {
console.log(this)
// STATE IS IMMUTABLE
// State cannot be changed!!
//this.state.counter += 1 // NO
// State can be replaced with a brand new STATE
// Whenever setState is called it will call render automatically
this.setState({
counter: this.state.counter + 1
})
// this.counter += 1
// console.log(this.counter)
}
render() {
console.log("RENDER")
return (
<div>
<h1>{this.state.counter}</h1>
<button onClick = {this.handleIncrement}>Increment</button>
</div>
)
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment