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

  1. 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).

  2. 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.

  3. 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.

  4. Render color swatch:

    • Render a visual representation of the currently selected color using selectedColor.

    • Display the hexCode alongside or below the swatch.

Code

import React, { useState } from 'react';

const Slider = ({ channel, value, onChange }) => {
  const handleChange = (event) => {
    onChange(channel, event.target.value);
  };

  return (
    <div className="slider">
      <label htmlFor={`slider-${channel}`}>{channel}</label>
      <input
        type="range"
        id={`slider-${channel}`}
        min="0"
        max="255"
        value={value}
        onChange={handleChange}
      />
    </div>
  );
};

const Swatch = ({ color, hexCode }) => {
  return (
    <div className="swatch">
      <div
        style={{
          backgroundColor: `rgb(${color.join(',')})`,
          width: '100%',
          height: '50px',
        }}
      />
      <p>{hexCode}</p>
    </div>
  );
};

const ColorPicker = () => {
  const [selectedColor, setSelectedColor] = useState([255, 0, 0]);
  const [hexCode, setHexCode] = useState('#ff0000');

  const handleSliderChange = (channel, value) => {
    const newColor = [...selectedColor];
    newColor[channel] = value;
    setSelectedColor(newColor);
    setHexCode(`#${newColor.map((v) => v.toString(16).padStart(2, '0')).join('')}`);
  };

  return (
    <div className="color-picker">
      <Slider channel="0" value={selectedColor[0]} onChange={handleSliderChange} />
      <Slider channel="1" value={selectedColor[1]} onChange={handleSliderChange} />
      <Slider channel="2" value={selectedColor[2]} onChange={handleSliderChange} />
      <Swatch color={selectedColor} hexCode={hexCode} />
    </div>
  );
};

export default ColorPicker;

Explanation

Slider Component:

  • Imports: React and useState 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 the value state and calls the provided onChange 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 the Slider and Swatch 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 the selectedColor state based on slider changes and calculates the new hexCode.

  • 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