1class App extends React.Component {
2
3state = { count: 0 }
4
5handleIncrement = () => {
6 this.setState({ count: this.state.count + 1 })
7}
8
9handleDecrement = () => {
10 this.setState({ count: this.state.count - 1 })
11}
12 render() {
13 return (
14 <div>
15 <div>
16 {this.state.count}
17 </div>
18 <button onClick={this.handleIncrement}>Increment by 1</button>
19 <button onClick={this.handleDecrement}>Decrement by 1</button>
20 </div>
21 )
22 }
23}
1class Example extends React.Component {
2 constructor(props) {
3 super(props);
4 this.state = {
5 count: 0
6 };
7 }
8
9 render() {
10 return (
11 <div>
12 <p>You clicked {this.state.count} times</p>
13 <button onClick={() => this.setState({ count: this.state.count + 1 })}>
14 Click me
15 </button>
16 </div>
17 );
18 }
19}
1class Clock extends React.Component {
2 constructor(props) {
3 super(props);
4 this.state = {date: new Date()};
5 }
6
7 componentDidMount() { }
8 componentWillUnmount() { }
9 render() {
10 return (
11 <div>
12 <h1>Hello, world!</h1>
13 <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
14 </div>
15 );
16 }
17}
1Functional Component
2const [counter, setCounter] = useState(0);
3
4setCouter(counter + 1);
1import React, {Component} from 'react';
2
3class ButtonCounter extends Component {
4 constructor() {
5 super()
6 // initial state has count set at 0
7 this.state = {
8 count: 0
9 }
10 }
11
12 handleClick = () => {
13 // when handleClick is called, newCount is set to whatever this.state.count is plus 1 PRIOR to calling this.setState
14 let newCount = this.state.count + 1
15 this.setState({
16 count: newCount
17 })
18 }
19
20 render() {
21 return (
22 <div>
23 <h1>{this.state.count}</h1>
24 <button onClick={this.handleClick}>Click Me</button>
25 </div>
26 )
27 }
28}
29
30export default ButtonCounter
31