3 - Color Picker with Hex Code Display

Description

Develop a React application that features a color picker component. Users should be able to select a color from the picker, and the corresponding hexadecimal (hex) code of the chosen color should be displayed prominently on the screen.

Algorithm

  1. State Management: Use React's useState hook to manage a state variable selectedColor to store the currently selected color.

  2. Color Picker Integration: Integrate a suitable color picker library or component into your React project. Popular options include React Color, Material UI ColorPicker, or custom-built solutions.

  3. Hex Code Handling: Upon color selection, obtain the hex code of the chosen color from the color picker component and update the selectedColor state variable accordingly.

  4. Hex Code Display: Render the hex code value stored in selectedColor within a designated UI element, such as a <p> or <span> tag.

Code

import React, { useState } from 'react';
import { SketchPicker } from 'react-color';

function ColorPickerApp() {
  const [selectedColor, setSelectedColor] = useState('#FFFFFF');

  const handleChangeComplete = (color) => {
    setSelectedColor(color.hex);
  };

  return (
    <div className="color-picker-app">
      <h1>Color Picker</h1>
      <SketchPicker color={selectedColor} onChangeComplete={handleChangeComplete} />
      <p>Selected Color Hex Code: {selectedColor}</p>
    </div>
  );
}

export default ColorPickerApp;

Explanation

  • useState Hook: Manages the selectedColor state variable to store the chosen color.

  • React Color Integration: Imports the SketchPicker component from the react-color library.

  • Color Selection: The handleChangeComplete function is triggered when a color is selected in the SketchPicker. It extracts the hex code from the selected color object and updates the selectedColor state.

  • Hex Code Rendering: The hex code stored in selectedColor is displayed within a <p> tag.

Additional Notes

  • Library Choice: The choice of color picker library may vary based on preferences and project requirements.

  • Customization: Explore customization options provided by the chosen library to tailor the appearance and functionality of the color picker.

  • Accessibility: Consider accessibility guidelines for color contrast and visual clarity when designing the color picker interface.

Last updated