react-best-gradient-color-picker

repository·main·Indexed 41 days ago

https://github.com/hxf31891/react-gradient-color-picker

A highly customizable color and gradient picker for React.js applications, supporting solid colors and complex CSS gradients. Version 3.0.14 includes a comprehensive ColorPicker component and a `useColorPicker` hook for programmatic state control, gradient manipulation (linear and radial), and color format conversions (Hex, HSL, HSV, CMYK). Features include an eye dropper, custom presets, localization support, and granular CSS styling for internal components.

Tokens
6.3K
Snippets
17
Records
22
Agent score
50%

What's inside react-best-gradient-color-picker

  1. How the useColorPicker hook works

    main

    The useColorPicker hook provides complete programmatic control over the picker. It allows you to access the current state (like which gradient point is selected) and manipulate the color values (like changing hue, saturation, or gradient type) without relying on the default UI. This is ideal for building custom UI controls that drive the picker.

    import React, { useState } from 'react'
    import ColorPicker, { useColorPicker } from 'react-best-gradient-color-picker'
    
    function MyApp() {
      const [color, setColor] = useState('linear-gradient(90deg, rgba(96,93,93,1) 0%, rgba(255,255,255,1) 100%)');
      const { setSolid, setGradient } = useColorPicker(color, setColor);
    
      return(
        <div>
          <button onClick={setSolid}>Solid</button>
          <button onClick={setGradient}>Gradient</button>
          <ColorPicker value={color} onChange={setColor} />
        </div>
       )
    }
  2. Install react-best-gradient-color-picker

    main

    Install the package using npm or yarn to use the customizable color and gradient picker in your React.js project.

    npm install react-best-gradient-color-picker
    # or
    yarn add react-best-gradient-color-picker
  3. Customize the ColorPicker UI with custom controls

    main

    You can build your own UI controls for the color picker by using the useColorPicker hook. This hook provides granular control over gradient types, degrees, color points, and RGBA values, allowing you to bypass the default UI components.

    import React, { useState } from 'react'
    import ColorPicker, { useColorPicker } from 'react-best-gradient-color-picker'
    
    function MyApp() {
      const [color, setColor] = useState('linear-gradient(90deg, rgba(96,93,93,1) 0%, rgba(255,255,255,1) 100%)');
      const { 
        gradientType, 
        setLinear, 
        setRadial, 
        addPoint, 
        deletePoint, 
        degrees, 
        setDegrees, 
        setPointLeft, 
        currentLeft, 
        selectedPoint 
      } = useColorPicker(color, setColor);
    
      return(
        <div>
          <button onClick={setLinear}>Linear</button>
          <button onClick={setRadial}>Radial</button>
          {gradientType === 'linear-gradient' && <input value={degrees} onChange={(e) => setDegrees(e.target.value)} />}
          <input value={currentLeft} onChange={(e) => setPointLeft(e.target.value)} />
          <button onClick={() => addPoint(50)}>Add Color</button>
          <button onClick={() => deletePoint(selectedPoint)}>Delete Color</button>
          <ColorPicker value={color} onChange={setColor} hideControls={true} />
        </div>
       )
    }
  4. Restrict ColorPicker to only gradients or only solid colors

    main

    To restrict the user to only selecting gradients, use the hideColorTypeBtns={true} prop and ensure the initial value is a gradient string. To restrict to only solid colors, do the inverse by providing a solid color as the initial value and hiding the gradient buttons.

    // Only Gradients
    <ColorPicker
      value="linear-gradient(90deg, rgba(96,93,93,1) 0%, rgba(255,255,255,1) 100%)"
      onChange={setColor}
      hideColorTypeBtns={true}
    />
  5. Customize ColorPicker locales

    main

    Pass a locales object to the ColorPicker component to translate UI text. The object should follow the structure of the internal control keys (e.g., CONTROLS).

    const customLocales = {
      CONTROLS: {
        SOLID: 'Obične',
        GRADIENT: 'Gradijent',
      },
    }
    
    <ColorPicker locales={customLocales} />
  6. Configure ColorPicker presets

    main

    You can pass an array of color strings to the presets prop of the ColorPicker component. Note that the array is sliced to the first 18 colors if more are provided. You can also use previousColors from the useColorPicker hook to provide a history of recently used colors as presets.

    // Using static presets
    const customPresets = [
      'rgba(34, 164, 65, 1)',
      'rgba(210, 18, 40, .5)',
      // ... up to 18 colors
    ]
    
    <ColorPicker value={color} onChange={setColor} presets={customPresets} />
    
    // Using recently used colors from the hook
    const { previousColors } = useColorPicker(color, setColor);
    <ColorPicker value={color} onChange={setColor} presets={previousColors} />
  7. Use the ColorPicker component

    main

    The ColorPicker component is the primary UI element. It accepts a value (an rgba or CSS gradient string) and an onChange handler to update the state. This is the simplest way to integrate the picker into your application.

    import React, { useState } from 'react'
    import ColorPicker from 'react-best-gradient-color-picker'
    
    function MyApp() {
      const [color, setColor] = useState('rgba(255,255,255,1)');
    
      return <ColorPicker value={color} onChange={setColor} />
    }
  8. Get gradient value as an object

    main

    The ColorPicker returns a CSS string via onChange. To get a structured JavaScript object representing the gradient (including type, degrees, and color stops), use the getGradientObject function from the useColorPicker hook.

    const { getGradientObject } = useColorPicker(color, setColor);
    const gradientObject = getGradientObject();
    
    // Resulting object structure:
    // {
    //   "isGradient": true,
    //   "gradientType": "linear-gradient",
    //   "degrees": "40deg",
    //   "colors": [
    //       { "value": "rgba(27,107,235,1)", "left": 0 },
    //       { "value": "rgba(25,245,157,1)", "left": 100 }
    //     ]
    // }
  9. Access state with useColorPicker

    main

    The useColorPicker hook provides access to the current internal state of the picker:

    NameDescription
    selectedPointIndex of the currently selected color point in a gradient
    isGradientBoolean indicating if the mode is solid or gradient
    gradientTypeCurrent gradient type (linear or radial)
    degreesCurrent degrees of the gradient
    currentLeftPosition of the selected gradient color
    rgbaArrCurrent RGBA values as an array
    hslArrCurrent HSL values as an array
  10. Use useColorPicker functions to manipulate color

    main

    The useColorPicker hook returns several functions to manipulate the color state and gradient structure.

    Gradient & Mode Control:

    • setLinear(): Change gradient type to linear.
    • setRadial(): Change gradient type to radial.
    • setDegrees(degrees: number): Change linear gradient degrees (0-360).
    • setSolid(rgbaString?: string): Switch to solid color mode.
    • setGradient(cssGradientString?: string): Switch to gradient mode.

    Color Component Control:

    • setR(value: number): Update Red (0-255).
    • setG(value: number): Update Green (0-255).
    • setB(value: number): Update Blue (0-255).
    • setA(value: number): Update Alpha/Opacity (0-100).
    • setHue(value: number): Update Hue (0-360).
    • setSaturation(value: number): Update Saturation (0-100).
    • setLightness(value: number): Update Lightness (0-100).

    Gradient Point Management:

    • handleChange(rgbaString: string): Update the color of the currently selected point without overwriting the entire gradient string.
    • setSelectedPoint(index: number): Update which gradient color point is in focus.
    • addPoint(position: number): Add a new color at a specific position (0-100).
    • deletePoint(index: number): Delete a color point.
    • setPointLeft(value: number): Update the position (0-100) of the selected point.

    Conversion & Data:

    • valueToHSL(), valueToHSV(), valueToHex(), valueToCmyk(): Get current value in specific formats.
    • getGradientObject(): Returns the gradient value parsed into a key/value object.
  11. Convert color values using useColorPicker

    main

    The useColorPicker hook provides utility functions to convert the current color state into various formats like HSL, HSV, Hex, and CMYK, as well as providing raw RGBA or HSL arrays.

    import React, { useState } from 'react'
    import ColorPicker, { useColorPicker } from 'react-best-gradient-color-picker'
    
    function MyApp() {
      const [color, setColor] = useState('linear-gradient(90deg, rgba(96,93,93,1) 0%, rgba(255,255,255,1) 100%)');
      const { 
        valueToHSL, 
        valueToHSV, 
        valueToHex, 
        valueToCmyk, 
        rgbaArr, 
        hslArr 
      } = useColorPicker(color, setColor);
    
      const hslString = valueToHSL();
      const hsvString = valueToHSV();
      const hexString = valueToHex();
      const cmykString = valueToCmyk();
      const rgbaArray = rgbaArr;
      const hslArray = hslArr;
    
      return <ColorPicker value={color} onChange={setColor} />
    }
  12. Configure internal component settings with PassedConfig

    main

    The PassedConfig object allows you to pass specific configuration values into the component via the config prop in ColorPickerProps.

    KeyTypeDescription
    barSizenumberSize of the color bars
    crossSizenumberSize of the crosshair/selector
    defaultColorstringThe default color value
    defaultGradientstringThe default gradient value
    export type PassedConfig = {
      barSize?: number
      crossSize?: number
      defaultColor?: string
      defaultGradient?: string
    }