36 - Interactive Color Picker with Sliders
Description
Create an interactive color picker tool using React.
Users adjust colors using sliders for red, green, and blue channels.
Preview the corresponding hex code of the selected color.
Optional enhancements: preset palettes, opacity control, color history, accessibility features.
Algorithm
Initialize state:
Create an array
selectedColor
to store RGB values (e.g., [255, 0, 0]).Create a string
hexCode
to store the hex code (e.g., #ff0000).
Render sliders:
For each color channel (red, green, blue):
Render a slider component with initial value from
selectedColor
.Attach an event listener to the slider's change event.
Handle slider changes:
When a slider changes:
Update the corresponding value in the
selectedColor
array.Calculate the new hex code using
selectedColor
values and string formatting.Update the
hexCode
state variable.Trigger a re-render to display the updated color swatch.
Render color swatch:
Render a visual representation of the currently selected color using
selectedColor
.Display the
hexCode
alongside or below the swatch.
Code
Explanation
Slider Component:
Imports:
React
anduseState
hook for state management.Functionality: Renders a single slider with a label and input range element.
Props:
channel
: String indicating the color channel (red, green, blue).value
: Integer representing the current slider value.onChange
: Function to handle slider changes, passing channel and value.
State: None.
Event Handling:
handleChange
: Updates thevalue
state and calls the providedonChange
function.
2. Swatch Component:
Imports:
React
.Functionality: Renders a visual representation of the selected color and its hex code.
Props:
color
: Array of RGB values representing the color.hexCode
: String representing the hex code of the color.
State: None.
Rendering:
Displays a div with a background color set to the
color
prop.Shows the
hexCode
below the color swatch.
3. ColorPicker Component:
Imports:
React
,useState
, and theSlider
andSwatch
components.Functionality: Main component managing state and rendering UI elements.
State:
selectedColor
: Array storing RGB values of the currently selected color.hexCode
: String representing the hex code of the selected color.
Event Handling:
handleSliderChange
: Updates theselectedColor
state based on slider changes and calculates the newhexCode
.
Rendering:
Renders three
Slider
components, one for each color channel.Renders a
Swatch
component to display the selected color and hex code.
Additional Notes
You'll need to style the components using CSS or a styling library for visual appeal.
Consider adding features like preset palettes, opacity control, and accessibility features as desired.
Last updated