Premium Only Content

React.js Box Component Color Controlled via Text Field
Continuing from the example of using the library React.js to build user interfaces. In this particular situation, a colored Box component whose color is controlled via a property. Now the goal is to change the color of a Box component using a text field.
Using the hook useState, you can keep track of another state variable to hold the color name. That value is tied to an input of attribute type having the value text. That input is placed next to the existing button to change the color.
You learn about controlled components, those whose value and onChange props are defined explicitly and controlled using a React state value. A function is defined to handle the changing of the text. That is, when the user types into the text field, the onChange handler function is called to update the value in state.
An event handler function has a parameter called event that includes details about who triggered the event. In particular, you can use the event target to access the input element so that you can retrieve the value that was typed by the user.
You can call on the mutate function for the color name to update its value after the user types into the text field. Then, the click handler for the button to change color is modified to set the Box component color prop to the value that was typed into the text field for the color name. That is, the click of the button takes the state value for color name and uses that as the prop passed to the Box component.
The lesson also briefly mentions how in the past React.js components used to be mostly written with classes instead of functions. But that paradigm has since been changed and writing functional components is more encouraged now. Questions about the order of JavaScript code statements are also addressed, like the definition of a function inside a function and the order the functions are defined.
-
LIVE
RaikenNight
4 hours ago $0.39 earnedExploring the Galaxy of No Mans Sky
213 watching -
LIVE
Spartan
5 hours agoRanked and Expedition 33 (NG+4 and all enemies Set to 10x health)
85 watching -
2:54:31
Jokeuhl Gaming and Chat
9 hours agoDARKTIDE - Warhammer 40k w/ Nubes and AoA
11.9K1 -
2:19:56
Nerdrotic
15 hours ago $1.07 earnedNerdrotic Nooner 513
46.2K2 -
BigTallRedneck
5 hours agoRANKED FINALS W OMEGA
16K1 -
LIVE
Eternal_Spartan
12 hours ago🟢 Eternal Spartan Plays Final Fantasy 7 Rebirth Ep. 3 | USMC Vet | Join the Best Chat on Rumble
63 watching -
1:39:52
megimu32
4 hours agoOTS: Ace Ventura & The Death of 90s Comedy
17K8 -
1:14:30
We Like Shooting
17 hours ago $1.13 earnedDouble Tap 426 (Gun Podcast)
13.4K2 -
4:32:32
Meisters of Madness
7 hours agoWuchang Returns with Madness & Ranked Finals
6.75K -
2:27:03
Illyes Jr Gaming
4 hours agoBlack Ops 6 Action Reppin @Mystivis
4.22K