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.
-
DVR
Scammer Payback
2 hours agoCalling Scammers Live
5.83K3 -
1:01:07
In The Litter Box w/ Jewels & Catturd
23 hours agoVOX POPULI, VOX DEI | In the Litter Box w/ Jewels & Catturd – Ep. 709 – 12/19/2024
49K26 -
22:54
Stephen Gardner
4 hours ago🔥JUST NOW: Trump JUST SHOCKED GOP with new DEMAND!!
34.1K33 -
1:23:22
Tate Speech by Andrew Tate
5 hours agoEMERGENCY MEETING EPISODE 96 - LAWFARE BREAKDOWN
156K119 -
16:53
DeVory Darkins
23 hours ago $12.95 earnedElon Musk Drops NIGHTMARE WARNING on Congress
35.1K210 -
1:29:17
Mally_Mouse
5 hours agoLet's Play!! - Stardew Valley
30.6K1 -
8:56
Melonie Mac
4 hours agoMy Superman Trailer Impressions
18.7K27 -
LIVE
StoneMountain64
5 hours ago☠️
176 watching -
36:08
Standpoint with Gabe Groisman
5 hours agoEp. 62. Understanding the Chaos in Syria. Dr. Jonathan Schanzer
29.4K4 -
3:52:39
Viss
5 hours ago🔴LIVE - Budget Zero To Hero Runs! - Delta Force
31.5K2