react-color-palette

repository·main·Indexed 43 days ago

https://github.com/wondermarin/react-color-palette

A lightweight color picker component library for React. It provides a comprehensive <ColorPicker /> component and granular sub-components including <Saturation />, <Hue />, and <Alpha /> for building customized color selection interfaces. Includes the useColor hook for managing color state across supported formats such as hex, named colors, and sRGB (rgb, hsl, hwb). Version 7.3.1.

Tokens
5.6K
Snippets
20
Records
28
Agent score
6%

What's inside react-color-palette

  1. How useColor handles different color formats

    main

    The useColor hook accepts an initial color value of type TColor. Supported formats include:

    • <named-color> (e.g., "cyan")
    • <hex-color> (e.g., "#123123")
    • sRGB color space using hsl(), hwb(), or rgb() functions (e.g., "rgb(86 30 203)" or "hsl(120 100% 50% / .5)").
  2. Create a custom color picker layout

    main

    If the standard <ColorPicker /> component does not meet your design needs, you can compose your own layout using the individual sub-components: <Saturation />, <Hue />, and <Alpha />. These components are exported separately and can be placed in any order or container.

    import { Saturation, Hue, useColor } from "react-color-palette";
    import "react-color-palette/css";
    
    export function App() {
      const [color, setColor] = useColor("hsl(120 100% 50% / .5)");
    
      return (
        <div className="custom-layout">
          <Saturation height={300} color={color} onChange={setColor} />
          <Hue color={color} onChange={setColor} />
        </div>
      );
    }
  3. Basic usage of ColorPicker and useColor

    main

    To use the color picker, import ColorPicker and the useColor hook. You must also import the library's CSS file for styles to apply. The useColor hook manages the color state, providing the current color and a setter function.

    import { ColorPicker, useColor } from "react-color-palette";
    import "react-color-palette/css";
    
    export function App() {
      const [color, setColor] = useColor("#561ecb");
    
      return <ColorPicker color={color} onChange={setColor} />;
    }
  4. Configure Saturation, Hue, and Alpha components

    main

    These sub-components can be used individually for custom layouts.

    Common Props for all three:

    • color (IColor): The current color.
    • disabled (boolean): Disables interactivity. Defaults to false.
    • onChange (Function): Callback fired when the color changes.
    • onChangeComplete (Function): Callback fired when the interaction is complete.

    Specific Props:

    • <Saturation />: height (number) - Height of the saturation element in pixels.
  5. Configure ColorPicker props

    main

    The <ColorPicker /> component is the main entry point. It includes <Saturation />, <Hue />, <Alpha />, and input fields.

    Props:

    • color (IColor): The current color.
    • onChange (Function): Callback fired when the color changes.
    • onChangeComplete (Function): Callback fired when the user interaction with the picker is finished.
    • hideInput ((keyof IColor)[] | boolean): If true, hides all inputs. If an array, hides only the specified input keys (e.g., ['rgb', 'hsv']).
    • hideAlpha (boolean): Hides the <Alpha /> component. Defaults to false.
    • disabled (boolean): Disables all interactivity. Defaults to false.
    • height (number): Height of the <Saturation /> component in pixels. Defaults to 200.
  6. Reference IColor and its sub-types

    main

    The IColor interface represents the color object used throughout the library.

    IColor structure:

    • hex (string)
    • rgb (IColorRgb)
    • hsv (IColorHsv)

    IColorRgb:

    • r (number)
    • g (number)
    • b (number)
    • a (number)

    IColorHsv:

    • h (number)
    • s (number)
    • v (number)
    • a (number)
    interface IColor {
      hex: string;
      rgb: IColorRgb;
      hsv: IColorHsv;
    }
    
    interface IColorRgb {
      r: number;
      g: number;
      b: number;
      a: number;
    }
    
    interface IColorHsv {
      h: number;
      s: number;
      v: number;
      a: number;
    }
  7. Use the interactive ColorPicker component

    main

    The react-color-palette package provides an interactive color picker component. While this entrypoint re-exports the contents of ./interactive.component, the primary way to use the library is by importing the ColorPicker component. This component allows users to select colors via a visual interface and provides callbacks for color changes.

    import { ColorPicker } from 'react-color-palette';
    import 'react-color-palette/css';
    
    // Usage example:
    // <ColorPicker color={color} onChange={setColor} />
  8. Use the Saturation component

    main

    The Saturation component is part of the react-color-palette library and is used to provide a saturation/lightness selection interface. It is exported from the saturation component entrypoint. To use it, import it from the package's saturation module.

    import { Saturation } from 'react-color-palette';
    
    // Usage within a color picker context
    <Saturation 
      color={color} 
      onChange={onChange} 
    />
  9. Use the Interactive component for coordinate tracking

    main

    The Interactive component is a wrapper used to capture mouse or touch coordinates relative to its own bounding box. This is useful for building custom color selection areas where you need to map user interaction (clicks/drags) to specific X and Y coordinates within a container.

    Props

    PropTypeDescription
    onCoordinateChange(final: boolean, x: number, y: number) => voidCallback triggered on move or end. final is true when the interaction ends (e.g., mouseup or touchend), and false during movement. x and y are clamped coordinates within the component's width and height.
    childrenReact.ReactNodeThe content to be rendered inside the interactive area.
    disabledboolean (optional)If true, sets aria-disabled on the container. Note that the component logic currently handles interaction via event listeners attached to the document, so ensure you manage the disabled state in your own event handlers if you wish to prevent movement.
    import { Interactive } from 'react-color-palette';
    
    // Example usage within a custom color picker component
    const MyCustomPicker = () => {
      const handleCoordinateChange = (isFinal: boolean, x: number, y: number) => {
        console.log(`Interaction: ${isFinal ? 'Ended' : 'Moving'} at x: ${x}, y: ${y}`);
        // Map x/y to a color value here
      };
    
      return (
        <Interactive onCoordinateChange={handleCoordinateChange}>
          <div style={{ width: 300, height: 300, background: 'linear-gradient(to right, red, blue)' }} />
        </Interactive>
      );
    };
  10. Use the Saturation component

    main

    The Saturation component is a slider used to select the saturation and value (brightness) of a color. It requires a height and the current color object, and it provides callbacks for color changes.

    Props

    PropTypeDescription
    heightnumberThe height of the saturation area in pixels.
    colorIColorThe current color object containing hsv and rgb properties.
    disabledboolean (optional)If true, interaction with the slider is disabled.
    onChange(color: IColor) => voidCallback triggered whenever the color changes during interaction.
    onChangeComplete(color: IColor) => void (optional)Callback triggered only when the user finishes the interaction (e.g., releases the mouse).
    <Saturation
      height={150}
      color={currentColor}
      onChange={(newColor) => setCurrentColor(newColor)}
      onChangeComplete={(finalColor) => console.log('Color selected:', finalColor)}
    />
  11. Configure the Fields component props

    main

    The Fields component provides input fields for HEX, RGB, and HSV color values. You can control its visibility, interactivity, and callback behavior using the following props:

    • color: An IColor object representing the current color state.
    • onChange: A callback function triggered on every input change.
    • onChangeComplete: An optional callback function triggered when an input field loses focus (onBlur). This is useful for validating or finalizing a color value after a user finishes typing.
    • hideInput: Determines which color fields are visible. It accepts either a boolean or an array of keys from IColor (e.g., ['hex', 'rgb', 'hsv']) to hide specific inputs.
    • disabled: A boolean that, when true, makes the input fields read-only.
    interface IFieldsProps {
      readonly hideInput: (keyof IColor)[] | boolean;
      readonly color: IColor;
      readonly disabled?: boolean;
      readonly onChange: (color: IColor) => void;
      readonly onChangeComplete?: (color: IColor) => void;
    }