Color Switcher
In this exercise, you are tasked with creating a simple Color Switcher component that allows users to change the background color of a div by selecting a color from a dropdown list.
Expectations:
Create a dropdown list with a few color options (e.g., red, blue, green, yellow)
When a color is selected from the dropdown, the background color of the div should change to the selected color
useState
hook to manage the background color state
Solution Walkthrough for Color Switcher
Spoiler Alert!
Don't read this unless you've already solved the problem.
bgColor
:bgColor
using the useState
hook. This variable will store the current background color of the div.const [bgColor, setBgColor] = useState('');
handleColorChange
function:handleColorChange
that updates the bgColor
state variable whenever a new color is selected from the dropdown. This function takes the event object as a parameter and sets the state using the selected color value.function handleColorChange(event) {
setBgColor(event.target.value);
}
handleColorChange
function:handleColorChange
function to the dropdown's onChange
event handler.<select onChange={handleColorChange}>
<option value="">Select a color</option>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="green">Green</option>
<option value="yellow">Yellow</option>
</select>
bgColor
state:bgColor
state variable. We also set the width and height of the div for better visibility.<div style={{ backgroundColor: bgColor, width: '100px', height: '100px' }}></div>
handleColorChange
function is called. This function updates the bgColor
state with the new color value, causing the background color of the div to change accordingly.