react-color

repository·main·Indexed 19 days ago

https://github.com/uiwjs/react-color

A suite of React color picker components including Chrome, Circle, Colorful, Compact, and Alpha. Features include HSVA color state management, native EyeDropper API support, customizable sliders, and color conversion utilities between RGBA and HSVA formats.

Tokens
11.7K
Snippets
38
Records
50
Agent score
69%

What's inside uiwjs-react-color

  1. Use custom lightness shades for specific colors

    main

    By default, the Slider uses the lightness prop to determine the value levels of the color blocks. However, you can use customColorShades to provide specialized lightness arrays for specific colors (e.g., different scales for black vs. white).

    When the current color matches a color defined in customColorShades (based on HSVA values within a tolerance), the component switches to that specific lightness array.

    Note: Matching is performed using HSVA values with a tolerance of 2 units.

    <Slider
      color="#000000"
      customColorShades={[
        {
          color: '#000000',
          lightness: [50, 40, 30, 20, 10]
        },
        {
          color: '#ffffff',
          lightness: [95, 90, 80, 70, 60]
        }
      ]}
      lightness={[80, 65, 50, 35, 20]} // Fallback lightness
    />
  2. Switch between color input types in Chrome

    main

    The Chrome component features an internal state that allows users to cycle through different color input formats by clicking the Arrow icon next to the editable input. The cycle follows this order:

    1. RGBA $\rightarrow$
    2. HSLA $\rightarrow$
    3. HEXA $\rightarrow$
    4. (Back to RGBA)

    This behavior is controlled by the inputType prop for the initial state and the ChromeInputType enum.

  3. Use the Interactive component for drag events

    main

    The Interactive component provides a way to handle interactive drag events (both mouse and touch) on a container element. It calculates the relative position of the interaction within the container and provides callbacks for when a drag starts (onDown) and while it is moving (onMove).

    Key features:

    • Unified Input Handling: Automatically handles both MouseEvent and TouchEvent.
    • Relative Positioning: The Interaction object passed to callbacks provides the position relative to the container's top-left corner.
    • Touch Optimization: Uses touch-action: none to prevent default browser scrolling during interaction.
    • Global Event Tracking: Once a drag starts, it tracks movement on the window to ensure smooth interaction even if the pointer leaves the container.
    import Interactive, { InteractiveProps } from 'packages/drag-event-interactive/src/index';
    
    // Example usage
    const MyColorPicker = () => {
      const handleDown = (offset, event) => {
        console.log('Drag started at:', offset);
      };
    
      const handleMove = (offset, event) => {
        console.log('Dragging at:', offset);
      };
    
      return (
        <Interactive 
          onDown={handleDown} 
          onMove={handleMove} 
          style={{ width: 200, height: 200, background: '#eee' }}
        />
      );
    };
  4. HueProps type definition

    main

    The HueProps interface defines the configuration for the Hue component. It extends AlphaProps but omits hsva and onChange to provide a specialized interface focused on the hue value.

    export interface HueProps extends Omit<AlphaProps, 'hsva' | 'onChange'> {
      onChange?: (newHue: { h: number }) => void;
      hue?: number;
    }
    
  5. Customize the input rendering with renderInput

    main

    If you want to use a custom UI component instead of the default HTML <input>, use the renderInput prop. This prop receives the computed inputProps (which include the internal value, onChange, onBlur, and id) and a ref to the input element.

    <EditableInput
      renderInput={(props, ref) => (
        <input
          {...props}
          ref={ref}
          className="my-custom-input-class"
        />
      )}
    />
  6. Use the Compact color picker component

    main

    The Compact component provides a condensed color picker interface including a color swatch, a hex input, and RGBA sliders. It is useful for space-constrained UI elements.

    Key Features

    • Color Swatch: A grid of colors for quick selection.
    • Hex Input: An editable text field to input hex codes directly.
    • RGBA Sliders: Controls for Hue, Saturation, Value, and Alpha.
    • Customization: Supports custom color palettes, addons, and custom rendering for the selected color indicator.
    import Compact from '@uiw/react-color-compact';
    
    function App() {
      return (
        <Compact
          color="#ff0000"
          onChange={(color) => console.log(color)}
        />
      );
    }
  7. Use the Alpha color picker component

    main

    The Alpha component is a React component used to select the alpha (transparency) value of a color. It accepts an hsva object representing the current color state and provides an onChange callback to update it.

    Key Props

    • hsva: An object of type HsvaColor (e.g., { h: 0, s: 75, v: 82, a: 1 }).
    • onChange: A callback function triggered when the alpha value changes. It receives the updated color object and an Interaction offset.
    • direction: Sets the orientation of the picker. Can be 'horizontal' (default) or 'vertical'.
    • reverse: A boolean that flips the alpha progression along the chosen axis.
    • width / height: CSS values to control the picker dimensions. Default height is 16px.
    • pointer: A function that returns a custom React component to serve as the picker's handle.
    import React, { useState } from 'react';
    import Alpha from '@uiw/react-color-alpha';
    import { HsvaColor } from '@uiw/color-convert';
    
    export const MyAlphaPicker = () => {
      const [hsva, setHsva] = useState<HsvaColor>({ h: 0, s: 75, v: 82, a: 1 });
    
      return (
        <Alpha
          hsva={hsva}
          onChange={({ a }) => {
            setHsva((prev) => ({ ...prev, a }));
          }}
        />
      );
    };
  8. Use the @uiw/react-color main entrypoint

    main

    The @uiw/react-color package acts as a central aggregator for various color picker components and utilities. Instead of importing from individual sub-packages, you can import all available color pickers and color conversion utilities from this single entrypoint.

    Available components include:

    • Pickers: Alpha, Block, Chrome, Circle, Colorful, Compact, EditableInput, EditableInputRGBA, EditableInputHSLA, Github, Hue, Material, Saturation, ShadeSlider, Sketch, Slider, Swatch, and Wheel.
    • Utilities: All exports from @uiw/color-convert are available through this package.
    import { Chrome, Compact, Wheel } from '@uiw/react-color';
    
    function MyComponent() {
      return (
        <>
          <Chrome />
          <Compact />
          <Wheel />
        </>
      );
    }
  9. Configure AlphaProps for the Alpha component

    main

    The AlphaProps interface defines the configuration for the Alpha component. It extends standard HTMLDivElement attributes (excluding onChange).

    PropTypeDefaultDescription
    hsvaHsvaColorRequiredThe current color state { h, s, v, a }
    direction'vertical' | 'horizontal''horizontal'The orientation of the slider
    reversebooleanfalseFlips the alpha progression along the axis
    widthCSS.Properties['width']-Picker width (e.g., '316px')
    heightCSS.Properties['height']16Picker height
    radiusCSS.Properties['borderRadius']0Set rounded corners
    backgroundstring-Set the background color
    bgPropsReact.HTMLAttributes<HTMLDivElement>{}Props for the background element
    innerPropsReact.HTMLAttributes<HTMLDivElement>{}Props for the interactive element
    pointerPropsPointerProps{}Props passed to the pointer component
    pointer(props: PointerProps) => JSX.Element-Custom pointer component function
    prefixClsstring'w-color-alpha'CSS class prefix
    onChange(newAlpha: { a: number }, offset: Interaction) => void-Callback when alpha changes
  10. Customize the color selection rectangle with rectRender

    main

    The rectRender prop allows you to override the default rendering of the color selection rectangle. It receives SwatchRectRenderProps and can be used to inject custom logic or UI (like an arrow element).

    If you provide a rectRender function, it will be used instead of the default Point component.

    export interface GithubRectRenderProps extends SwatchRectRenderProps {
      arrow?: JSX.Element;
    }
  11. Check if the EyeDropper API is supported

    main

    Use the getIsEyeDropperSupported function to determine if the browser supports the native EyeDropper API. This is useful for conditionally rendering the EyeDropper component or providing fallback UI.

    import { getIsEyeDropperSupported } from '@uiw/react-color-chrome';
    
    if (getIsEyeDropperSupported()) {
      // Render EyeDropper component
    }