Random Color Input

By Thomas Kim

Generate a random color 🌈

theme.js

import RandomColor from '../../components'

export default {
  name: 'theme',
  type: 'document',
  fields: [
    {
      name: 'color',
      type: 'string',
      description: 'Enter a valid <format> value or generate one.',
      options: {
        // Available options: https://www.npmjs.com/package/randomcolor
        hue: 'orange',
        luminosity: 'bright',
        format: 'hsla',
        alpha: 0.25,
      },
      inputComponent: RandomColor,
    },
  ],
}

randomColor.jsx

import React from 'react'
import { FormField } from '@sanity/base/components'
import { Flex, Box, TextInput, Button } from '@sanity/ui'
import PatchEvent, { set, unset } from '@sanity/form-builder/PatchEvent'
import { useId } from '@reach/auto-id'
import randomColor from 'randomColor'

const RandomColor = React.forwardRef((props, ref) => {
  const {
    type,
    value,
    placeholder,
    markers,
    presence,
    compareValue,
    onFocus,
    onBlur,
    onChange,
  } = props

  // Creates a unique ID for our input
  const inputId = useId()

  // Destructure available options
  const { hue, luminosity, format, alpha } = type.options

  // Generates random color
  const color = randomColor({ hue, luminosity, format, alpha })

  const handleChange = React.useCallback(event => {
      const inputValue = event.currentTarget.value
      
      onChange(PatchEvent.from(inputValue ? set(inputValue) : unset()))
    },
    [onChange]
  )

  const handleClick = () => {
    onChange(PatchEvent.from(set(color)))
  }

  return (
    <FormField
      description={type.description}
      title={type.title}
      __unstable_markers={markers}
      __unstable_presence={presence}
      compareValue={compareValue}
      inputId={inputId}
    >
      <Flex align="center">
        <Box
          style={{
            width: 36,
            height: 36,
            borderRadius: 4,
            boxShadow: 'inset 0 0 0 1px #bfc1d1',
            backgroundColor: value || '#bfc1d1',
          }}
        />
        <Box flex={1} marginX={1}>
          <TextInput
            id={inputId}
            value={value}
            onChange={handleChange}
            placeholder={placeholder}
            onFocus={onFocus}
            onBlur={onBlur}
            ref={ref}
          />
        </Box>
        <Button text="Generate" mode="ghost" onClick={handleClick} />
      </Flex>
    </FormField>
  )
})

export default RandomColor

Generate a random color value with useful options. Based on the randomcolor package.

Features:

  • Displays color swatch 🎨
  • Acccepts hue, luminosity, format, and alpha options βš™οΈ
  • Customizable with your own value πŸ”«

Contributor