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
LFA TV
17 hours agoJOHN FETTERMAN JOINS TRUTH SOCIAL?! | LIVE WITH HANNAH FAULKNER 12.11.24 3pm EST
297 watching -
Silver Dragons
2 hours agoDealer Reveals Test for Fake Silver & Gold - DON'T GET SCAMMED!
184 -
2:09:30
PMG
22 hours ago $0.16 earned"Mike Benz: Is Mark Zuckerberg Coming Clean About Censorship?"
4794 -
8:36
Colion Noir
16 hours agoThe Media Is Blaming Ghost Guns For United Healthcare CEO Shooting
13.9K33 -
LIVE
The New American
1 hour agoLuigi Mangione’s Manifesto: The Healthcare System Made Me Do It | The New American Daily
674 watching -
LIVE
The Kevin Trudeau Show
4 hours agoDelay, Deny, Depose: The U.S. Healthcare System Is Killing Us | Ep. 73
271 watching -
30:39
The Boomer Effect
17 hours agoReimagining America's Dream
15.1K -
LIVE
hambinooo
4 hours ago*live* DELTA FORCE FULL PC LAUNCH
187 watching -
59:30
The Dan Bongino Show
5 hours agoWhat The Hell Is In the NJ Skies? (Ep. 2386) - 12/11/2024
728K2.46K -
2:10:37
Steven Crowder
6 hours ago🔴 How Trump Buried Leftwing Media & Conspiracy Talk
431K244