RHF-MUI Components
NPM

RHFColorPicker

RHFColorPicker wraps react-color-palette with label, error and helper-text handling, bound to React Hook Form through control. The stored value is a string, in the format chosen with valueKey.

Installation

Make sure to install the react-color-palette package before using this component.

npm install react-color-palette
yarn add react-color-palette
pnpm add react-color-palette

Usage

import RHFColorPicker, { RHFColorPickerProps } from '@nish1896/rhf-mui-components/misc/color-picker';
import { useForm } from 'react-hook-form';

type FormValues = {
  brandColor: string;
};

const { control, handleSubmit } = useForm<FormValues>({
  defaultValues: { brandColor: '#1976d2' }
});

<form onSubmit={handleSubmit(values => console.log(values.brandColor))}>
  <RHFColorPicker
    fieldName="brandColor"
    control={control}
    defaultColor="#007ABA"
  />
</form>

The color picker accepts string values in hex, rgb, hsl, or text format, such as:

  • #00ffff
  • rgb(0 255 255)
  • hsl(180 100% 100% / 1)
  • cyan

If the field value is uninitialized, the default color black (#000000) is selected, which can be configured using the defaultColor prop. Refer to the colorToString function to convert an RGB or HSV color object into a string, which can be used to set the default color for the color picker.

<RHFColorPicker
  fieldName="brandColor"
  control={control}
  onValueChange={color => console.log(color.hex, color.rgb)}
/>

Choosing the value format

valueKey decides which format is stored in the form: 'hex' (the default), 'rgb' or 'hsv'. The color object passed to onValueChange always carries all three, so use it when you need more than one format.

With valueKey="hsv", the picker renders only the saturation panel and the hue slider, without the text inputs or the alpha slider.

<RHFColorPicker
  fieldName="accent"
  control={control}
  valueKey="rgb"
/>

Customizing the picker

  • excludeAlpha drops the alpha channel from the stored value, for example #00ffff instead of #00ffffff.
  • hideAlpha hides the alpha slider, and hideInput hides some or all of the hex, rgb and hsv text inputs.
  • height sets the height, in pixels, of the saturation panel. It defaults to 200.
<RHFColorPicker
  fieldName="accent"
  control={control}
  excludeAlpha
  hideAlpha
  hideInput={['rgb', 'hsv']}
  height={240}
/>

Handling value changes

Two props let you respond to the user picking a color. Use onValueChange to run side effects once the color has been stored, and customOnChange to take over what gets stored in the form.

onValueChange

onValueChange runs after the color has been stored in the form. It receives the color object from react-color-palette, which carries the hex, rgb and hsv values.

<RHFColorPicker
  fieldName="brandColor"
  control={control}
  onValueChange={color => console.log(color.hex, color.rgb)}
/>

The below object denotes the shape of color obtained from onValueChange.

{
  hex: '#00ffff',
  hsv: {
    a: 1,
    h: 180,
    s: 100,
    v: 100
  },
  rgb: {
    a: 1,
    b: 255,
    g: 255,
    r: 0
  }
}

customOnChange

Use customOnChange when you need to change what gets stored. It replaces the default handling and receives { color, setColor }: the new color object, and a helper that updates both the picker and the form value. Call setColor with the color to commit; if you don't, nothing is stored. This example rejects colors that are too dark. onValueChange is not called when customOnChange is used.

<RHFColorPicker
  fieldName="accent"
  control={control}
  customOnChange={({ color, setColor }) => {
    if (color.hsv.v >= 20) {
      setColor(color);
    }
  }}
/>

Validation, labels and disabling

Rules go in registerOptions, for example a validate function to restrict the allowed colors. showLabelAboveFormField defaults to true. helperText, renderError, hideErrorMessage and disabled (or a form-level disabled in useForm) work as described in RHFTextField.

<RHFColorPicker
  fieldName="brandColor"
  control={control}
  registerOptions={{
    validate: value => value !== '#ffffff' || 'White is not allowed'
  }}
/>

Examples

Alternatives

If this package doesn't meet your requirements, consider the react-color package.

API

RHFColorPickerProps extends the props of ColorPicker and accepts the following additional props. Props marked with * are required.

NameTypeDescription
fieldName*string
Name of the field registered with React Hook Form. This prop is required for all components.
control*UseFormControl
The control option yielded on calling the useForm hook.
registerOptionsRegisterOptions
React Hook Form validation rules. Useful when not using a schema validation library such as Yup or Joi.
valueKeyhex / rgb / hsv
Determines the format of the selected color value. Returns a hex, rgba, or hsva representation of the selected color. When excludeAlpha is enabled, alpha information is omitted from the returned value.
Default value: hex.
defaultColorstring
The default color to select when the field is not initialized. Provide a valid color string, hex, rgb or hsv value.
Default value: Black(#000000)
excludeAlphaboolean
Specifies whether to exclude alpha from the color string when the valueKey is rgb or hsv. Alpha will only be excluded if its value is 1 or is undefined in the input color.
requiredboolean
Indicates that the field is mandatory by adding an asterisk symbol (*) to the formLabel. This visual cue helps users quickly identify required fields in the form.
onValueChange(color: IColor) => void
Callback function to get the selected color in hex, rgb or hsv format. The color format being set in field value can be configured by the valueKey prop.
customOnChange({ color, setColor }) => void
An optional callback function to override the default onChange behavior of the color picker component. This invalidates the usage of onValueChange function. You can get the selected color value and the setColor function from the parameters to implement your custom logic and update the form state.
disabledboolean
Disables the component and prevents user interaction.
labelReactNode
The text to render in the FormLabel component. By default, the value of fieldName is transformed (e.g., "firstName" to "First Name") using the fieldNameToLabel function.
showLabelAboveFormFieldboolean
Renders the form label above the field.
formLabelPropsFormLabelProps
FormLabelProps to customise FormLabel component for a field. Multiple fields can be configured using the ConfigProvider component.
hideLabelboolean
Hides the FormLabel component if you don’t want to display the default form label component or prefer to render a fully custom label instead.
renderError(error: FieldError) => ReactNode
Custom renderer for the React Hook Form field error. Receives the current field error and returns the content to display, such as error.message or a custom React element in the HelperText component.
Added in v4.1.0.
hideErrorMessageboolean
A flag to prevent replacement of helper text of a field by the errorMessage when the validation is triggered.
helperTextReactNode
The content to display within the FormHelperText component below the field. If the field validation fails, this content will be overridden by the corresponding error message.
formHelperTextPropsFormHelperTextProps
FormHelperTextProps to customise FormHelperText component for a field. Multiple fields can be configured using the ConfigProvider component.
customIds{ field, label, helperText, error }
Overrides the default field, label, helper text, and error IDs used for accessibility.

Source Code

View the full implementation of this component on GitHub.