logo
logo

Color Switcher

Medium

Color Switcher

Medium

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

  • Use the
    useState
    hook to manage the background color state

Console
Solution
00:00

Solution Walkthrough for Color Switcher

Solution Walkthrough:

Initialize the state variable
bgColor
:
We create a state variable called
bgColor
using the
useState
hook. This variable will store the current background color of the div.
const [bgColor, setBgColor] = useState('');
Create the
handleColorChange
function:
We define a function called
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);
}
Render the dropdown with color options and attach the
handleColorChange
function:
In the return statement, we render a dropdown list with color options (red, blue, green, and yellow). We attach the
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>
Create a div and set its background color based on the
bgColor
state:
We create a div element and use inline styling to set its background color. The background color is determined by the current value of the
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>
When the user selects a color from the dropdown list, the
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.