@@ -82,7 +82,7 @@ to build out this feature.
82
82
Any time we need state in a component, we need to use the ` useState ` hook from
83
83
React. We can import it like so:
84
84
85
- ``` js
85
+ ``` jsx
86
86
import React , { useState } from " react" ;
87
87
```
88
88
@@ -91,7 +91,7 @@ import React, { useState } from "react";
91
91
To create a state variable in our component, we need to call ` useState ` and
92
92
provide an initial value:
93
93
94
- ``` js
94
+ ``` jsx
95
95
function Toggle () {
96
96
const [isOn , setIsOn ] = useState (false );
97
97
// ... the rest of Toggle component
@@ -107,7 +107,7 @@ We're setting the initial state here as `false`, because the button should be
107
107
Now that we have this new variable, it's time to use it! We can use the ` isOn `
108
108
variable to determine what text to display in the button:
109
109
110
- ``` js
110
+ ``` jsx
111
111
< button> {isOn ? " ON" : " OFF" }< / button>
112
112
```
113
113
@@ -127,7 +127,7 @@ update. In our case it's the button being clicked.
127
127
128
128
Let's start by adding an ` onClick ` handler to the button:
129
129
130
- ``` js
130
+ ``` jsx
131
131
< button onClick= {handleClick}> {isOn ? " ON" : " OFF" }< / button>
132
132
```
133
133
@@ -136,7 +136,7 @@ we must call the _setter function_ to update our state variable. Trying to
136
136
update the variable directly won't have any effect (even if we changed our
137
137
variable declaration to ` let ` instead of ` const ` ):
138
138
139
- ``` js
139
+ ``` jsx
140
140
let [isOn, setIsOn] = useState (false );
141
141
function handleClick () {
142
142
// updating state directly is a no-no!
@@ -146,15 +146,15 @@ function handleClick() {
146
146
147
147
So the way we should update state looks like this:
148
148
149
- ``` js
149
+ ``` jsx
150
150
function handleClick () {
151
151
setIsOn ((isOn ) => ! isOn);
152
152
}
153
153
```
154
154
155
155
All together, here's our updated component:
156
156
157
- ``` js
157
+ ``` jsx
158
158
function Toggle () {
159
159
const [isOn , setIsOn ] = useState (false );
160
160
@@ -171,7 +171,7 @@ function Toggle() {
171
171
With this state variable in place, let's add another feature to our button. When
172
172
the button is ON, let's make the background red, like this:
173
173
174
- ``` js
174
+ ``` jsx
175
175
< button style= {{ background: " red" }}>
176
176
```
177
177
0 commit comments