Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-best-gradient-color-picker

Package Overview
Dependencies
Maintainers
0
Versions
224
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-best-gradient-color-picker

An easy to use color/gradient picker for React.js

  • 3.0.11
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
13K
increased by2.5%
Maintainers
0
Weekly downloads
 
Created
Source

Npm Version Downloads License

react-best-gradient-color-picker

  • Customizable, easy to use color and gradient picker for React.js
  • Simply pass in an rgba or css gradient string as value and an onChange handler
  • Variety of optional tools like eye dropper, advanced color settings, and color guide
  • use the useColorPicker hook for complete control over of the picker
  • You can completly customize the UI by hiding the included elements and using the hook to build your own
  • You can also customize preset options by passing in an array of rgba colors (see custom presets below)


Install

npm install react-best-gradient-color-picker
yarn add react-best-gradient-color-picker

Demo

See the picker in action here


Table of Contents


Basic Example

import React 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} />
}

Props

NameTypeDefaultDescription
valuestring'rgba(175, 51, 242, 1)'The starting color
widthint294(optional) The width of the picker
heightint294(optional) The height of the picker
hideInputsbooleanfalse(optional) hide the hex and rgba inputs
hideOpacitybooleanfalse(optional) hide the opacity bar
hideHuebooleanfalse(optional) hide the hue bar
hideControlsbooleanfalse(optional) hide the entire top row of various control btns
hideColorTypeBtnsbooleanfalse(optional) hide the solid/gradient buttons
hidePresetsbooleanfalse(optional) hide the preset color options
hideEyeDropbooleanfalse(optional) hide (and disable the eye dropper tool
hideAdvancedSlidersbooleanfalse(optional) hide the additional sliders (saturation, luminence, brightness
hideColorGuidebooleanfalse(optional) hide the color guide, a tool that shows color pairings
hideInputTypebooleanfalse(optional) hide the input type selector, looking the type
hideGradientTypebooleanfalse(optional) hide the linear/circular gradient type toggle (only relevant in gradient mode)
hideGradientAnglebooleanfalse(optional) hide the gradient angle input (only relevant in gradient mode with a linear gradient)
hideGradientStopbooleanfalse(optional) hide the gradient point stop input (only relevant in gradient mode)
hideGradientControlsbooleanfalse(optional) hide the all gradient controls (the bar that appears below top controls when in gradient mode)
presetsarray['rgba(0,0,0,1)', ...](optional) pass in custom preset options ['rgba()', 'rgba()', ..]
localesobject{ CONTROLS: { SOLID: 'Solid', GRADIENT: 'Gradient' }}(optional) pass in custom locales
disbaleDarkModebooleanfalse(optional) disbale automatic dark mode style adjustments
classNamestring''(optional) a CSS class for the picker parent (see styling for more options)

API

NameDescription
onChangeA function to update color value

useColorPicker

  • Take complete control of the picker
  • Get current state
  • Convert between color types

Basic Example

  • Initialize the hook by passing in the same color value and onChange handler
import React 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>
   )
}

Included Functions

NameArgumentsDescription
handleChangevalue (rgba string)Most useful for setting color value of the selectedPoint without overwriting entire gradient string. Only pass this function a single color value, not a gradient
setLinearChange the type of gradient to linear
setRadialChange the type of gradient to radial
setDegreesdegrees (num, 0 - 360)Change the degrees of a linear gradient
setSolid(optional) new solid color (rgba string)Change the pickers color mode from gradient to solid
setGradient(optional) new gradient (CSS gradient)Change the pickers color mode from solid to gradient
setRvalue (num, 0 - 255)Update the red value of the color
setGvalue (num, 0 - 255)Update the green value of the color
setBvalue (num, 0 - 255)Update the blue value of the color
setAvalue (num, 0 - 100)Update the opacity (alpha) of a color
setHuevalue (num, 0 - 360)Update the hue of a color
setSaturationvalue (num, 0 - 100)Update the saturation of a color
setLightnessvalue (num, 0 - 100)Update the lightness of a color
valueToHSLGet the current value in HSL
valueToHSVGet the current value in HSV
valueToHexGet the current value in HEX
valueToCmykGet the current value in CMYK
setSelectedPointindex of point (num)Update which individual color of a gradient is in focus
deletePointindex of point (num)Delete one of the gradients colors
addPointposition of point (num, 0 - 100)Add a new color to the gradient
setPointLeftvalue (num, 0 - 100)Update the position (left) of the currently selected gradient color
getGradientObjectget the gradients value parsed into a key/value object (see example below)

Available State

NameDescription
selectedPointreturns index of which color point of a gradient is currently selected
isGradientreturns which mode the picker is in, solid or gradient
gradientTypewhich gradient type is currently selected, linear or radial
degreescurrent degrees of a radial gradient
currentLeftthe position of the selected gradient color
rgbaArrget the current rgba values in an array
hslArrget the current hsl values in an array

Various Customization Examples

Custom Gradient Controls

import React 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>
   )
}

Custom RGBA Inputs

import React 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 { setR, setG, setB, setA, rgbaArr } = useColorPicker(color, setColor);

  return(
    <div>
      <input value={rgbaArr[0]} onChange={(e) => setR(e.target.value)} />
      <input value={rgbaArr[1]} onChange={(e) => setG(e.target.value)} />
      <input value={rgbaArr[2]} onChange={(e) => setB(e.target.value)} />
      <input value={rgbaArr[3]} onChange={(e) => setA(e.target.value)} />
      <ColorPicker value={color} onChange={setColor} hideInputs={true} />
    </div>
   )
}

Conversions

import React 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(
    <div>
      <ColorPicker value={color} onChange={setColor} />
    </div>
   )
}

Custom Presets Example

import React from 'react'
import ColorPicker from 'react-best-gradient-color-picker'

const customPresets = [
  'rgba(34, 164, 65, 1)',
  'rgba(210, 18, 40, .5)',
  'rgba(90, 110, 232, 1)',
  'rgba(65, 89, 56, 1)',
  'rgba(98, 189, 243, 1)',
  'rgba(255, 210, 198, 1)',
  'rgba(94, 94, 94, 1)'
] //max 18 colors, you can pass in more but the array will be sliced to the first 18

function MyApp() {
  const [color, setColor] = useState('rgba(255,255,255,1');

  return <ColorPicker value={color} onChange={setColor} presets={customPresets} />
}

You may also want to provide the users recently used colors in lieu of preset options. This can be easily accomplished use the hook.

import React 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 { previousColors } = useColorPicker(color, setColor);

  return(
    <div>
      <ColorPicker value={color} onChange={setColor} presets={previousColors} />
    </div>
   )
}

Custom Locales Example

You can pass custom locales via locales prop.

import React from 'react'
import ColorPicker, { useColorPicker } from 'react-best-gradient-color-picker'

function MyApp() {
  const customLocales = {
    CONTROLS: {
      SOLID: 'Obične',
      GRADIENT: 'Gradijent',
    },
  }
  return (
    <div>
      <ColorPicker locales={customLocales} />
    </div>
  )
}

Getting Value in Object Form

The picker returns the new value as a css gradient string but you may need it parsed as an object. This can easily be accomplised by using the getGradientObject function returned by the useColorPicker hook like so:

import React 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 { getGradientObject } = useColorPicker(color, setColor);
  const gradientObject = getGradientObject();
  
  // example value
  // {
  //   "isGradient": true,
  //   "gradientType": "linear-gradient",
  //   "degrees": "40deg",
  //   "colors": [
  //       {
  //           "value": "rgba(27,107,235,1)",
  //           "left": 0
  //       },
  //       {
  //           "value": "rgba(25,245,157,1)",
  //           "left": 100
  //       }
  //     ]
  // }

  return(
    <div>
      <ColorPicker value={color} onChange={setColor} presets={previousColors} />
    </div>
   )
}

Only Gradients Example

If you would like to not allow selection of solid colors disable the color type buttons and feed in the initial value as a gradient like below:

NOTE: the same can be done in reverse to only allow selection of solid colors

import React 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%)');  

  return(
    <div>
      <ColorPicker
        value={color}
        onChange={setColor}
        hideColorTypeBtns={true}
      />
    </div>
   )
}

Styling

Many of the pickers components have css classnames you can target to change styles. Below are some of the more common, others can be found using the elements inspector.

ClassDescription
rbgcp-control-btn-wrappergrey area around the buttons
rbgcp-control-icon-btnicon buttons
rbgcp-control-btntext buttons
rbgcp-control-btn-selectedselected buttons, icon and text
rbgcp-color-model-dropdowndropdown to select between color modes
rbgcp-control-inputinputs on the gradient control bar, angle and stop
rbgcp-inputcolor value inputs, hex, rgba etc

LEGACY V1 - Manual Control - Customizing UI

This still works, although most functions are available through the useColorPicker hook, if there is something you need that is not available you could use the below methods to create your desired functionality.

The state of the picker is determined by parsing the value string. You can update props like colorType (solid/gradient), gradientType (linear/radial), gradientDegrees, hex, rgba, opacity and hue simply by updating the value you are passing into the component. Let's say you want to change the colorType from gradient to solid:

import React from 'react'
import ColorPicker 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 = () => {
    setColor('rgba(255,255,255,1)') //color could be any rgba value
  }

  return(
    <div>
      <button onClick={setSolid}>Solid</button>
      <ColorPicker value={color} onChange={setColor} />
    </div>
   )
}

The same can be done in inverse to change colorType from solid to gradient:

  const setGradient = () => {
    setColor('linear-gradient(90deg, rgba(96,93,93,1) 0%, rgba(255,255,255,1) 100%)')
  }

Example toggling gradientType

  const setLinear = () => {
    setColor('linear-gradient(90deg, rgba(96,93,93,1) 0%, rgba(255,255,255,1) 100%)')
  }
  
  const setRadial = () => {
    setColor('radial-gradient(circle, rgba(96,93,93,1) 0%, rgba(255,255,255,1) 100%)')
  }

Custom linear-gradient degrees input

import React from 'react'
import ColorPicker 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 degrees = parseInt(value?.split(',')[0]?.split('(')[1])
  
  const handleDegrees = (val) => {
    let num = parseInt(val)
    let nans = isNaN(num) ? 0 : num
    let min = Math.max(nans, 0)
    let max = Math.min(min, 360)
    const remaining = value.split(/,(.+)/)[1]
    setColor(`linear-gradient(${max}deg, ${remaining}`)
  }

  return(
    <div>
      <input value={degrees} onChange={(e) => handleDegrees(e.target.value)} />
      <ColorPicker value={color} onChange={setColor} />
    </div>
   )
}

Roadmap

  1. enhanced mobile support
  2. cross browser eye dropper issue
  3. enhanced gradient parsing to allow additional gradient types

License

Code released under the MIT license.

Acknowledgments

Very special thank you to Rafael Carício for his amazing work parsing gradient strings.

Keywords

FAQs

Package last updated on 08 Nov 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc