😎 Discover cool tips and tricks for customization in our next Developer Deep Dive virtual event - sign up now!

Time Custom Input Component

By Geoff Ball

A custom input component that lets users enter a time without requiring a date.

Your input component file (e.g., time-input.js)

import React from 'react';
import FormField from 'part:@sanity/components/formfields/default'
import {PatchEvent, set} from 'part:@sanity/form-builder/patch-event'
import {TextInput} from '@sanity/ui'

export const TimeInput = React.forwardRef((props, ref) => {
  const { type, onChange, value } = props;
  const { title, description } = type;
  return (
    <FormField label={title} description={description}>
      <TextInput
        type="time"
        ref={ref}
        value={value}
        onChange={event => {onChange(PatchEvent.from(set(event.target.value)))}}
      />
    </FormField>
  );
})

Your schema file

import { TimeInput } from '../path/to/time-input';

export default {
  name: "documentName",
  title: "Document Name",
  type: "document",
  fields: [

    // ...,

    {
      name: 'time',
      title: 'Time',
      type: 'string',
      description: 'Please enter a time.',
      inputComponent: TimeInput,
    },

    // ...

  ],
}

The Datetime schema type built into Sanity is useful, but sometimes you only want to work with times. Using a custom input component, we can add an HTML input with type="time", which will not require a date and stores the value consistently (as a string in 24-hour format).

The description property is optional.

The name and file location of your input component do not matter—you just need to be able to import the file into your schema.

  1. Create a file for your input component (I used time-input.js and put it in a components/ directory in the root of my studio).
  2. Add the input component code into time-input.js.
  3. In your schema file, do a named import of TimeInput:

    import { TimeInput } from '../path/to/time-input';
  4. In that same schema file, add an object with a type of string and an inputComponent property of TimeInput.

Contributor

Other schemas by author

Matching the end of a string in GROQ

GROQ doesn't yet include a function to match the end of a string, but we can simulate it by splitting our string on our term.

Geoff Ball
Go to Matching the end of a string in GROQ