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
1// Correct
2this.setState(function(state, props) {
3 return {
4 counter: state.counter + props.increment
5 };
6});
1class Car extends React.Component {
2 constructor(props) {
3 super(props);
4 this.state = {
5 brand: "Ford",
6 model: "Mustang",
7 color: "red",
8 year: 1964
9 };
10 }
11 changeColor = () => {
12 this.setState({color: "blue"});
13 }
14 render() {
15 return (
16 <div>
17 <h1>My {this.state.brand}</h1>
18 <p>
19 It is a {this.state.color}
20 {this.state.model}
21 from {this.state.year}.
22 </p>
23 <button
24 type="button"
25 onClick={this.changeColor}
26 >Change color</button>
27 </div>
28 );
29 }
30}
1 const [a, b] = React.useState(['hi','world']);
2 const dup = [...a]; //won't work without spread operator
3 b(dup);
1You have to use setState() for updating state in React
2{
3 hasBeenClicked: false,
4 currentTheme: 'blue',
5}
6
7setState({
8 hasBeenClicked: true
9});
10
1You have to use setState() for updating state in React
2{
3 hasBeenClicked: false,
4 currentTheme: 'blue',
5}
6
7setState({
8 hasBeenClicked: true
9});