Conditional field

The conditional field is used when you need to display entirely different fields based on a condition.

In the first argument, define the condition by using either a checkbox or a select field.

In the second argument, define which field(s) to display for each condition by passing an object with each conditions' value as a key:

  • true/false if you used a checkbox field, or
  • each possible value if you used a select field.

Usage examples

Checkbox

Let's say you want to optionally display SEO title/description fields, but only if a user checks a checkbox.

seo: fields.conditional(
  // First, we define a checkbox to drive the yes/no condition
  fields.checkbox({ label: 'Define custom SEO tags', defaultValue: false }),
  // Then, we provide a set of fields for both the `true` and `false` scenarios
  {
    true: fields.object({
      title: fields.text({ label: 'Title' }),
      description: fields.text({ label: 'Description' }),
    }),
    // Empty fields are useful to show... no fields!
    false: fields.empty(),
  }
)

Select

Here's a more complex example where you have an optional Featured media field for an entry.

The options for it are noneimage and video.

// Featured media
featuredMedia: fields.conditional(
  // First, define a `select` field with all the available "conditions"
  fields.select({
    label: 'Featured media',
    description: 'Optional image/video options for an optional hero media.',
    options: [
      { label: 'No media', value: 'none' },
      { label: 'Image', value: 'image' },
      { label: 'Video', value: 'video' },
    ],
    defaultValue: 'none',
  }),
  // Then, provide a schema for each condition
  {
    // "none" condition
    none: fields.empty(),
    // "image" condition
    image: fields.object({
      asset: fields.image({
        label: 'Image',
        directory: 'public/images/events',
        publicPath: '/images/events/',
        validation: { isRequired: true },
      }),
      alt: fields.text({ label: 'Alt', description: 'Image alt text.' }),
    }),
    // "video" condition
    video: fields.object({
      url: fields.text({
        label: 'A YouTube video URL.',
        validation: { length: { min: 1 } },
      }),
      image: fields.object({
        asset: fields.image({
          label: 'Image',
          description: 'Thumbnail image override for the video.',
          directory: 'public/images/events',
          publicPath: '/images/events/',
        }),
        alt: fields.text({ label: 'Alt', description: 'Image alt text.' }),
      }),
    }),
  }
),

Type signature

Find the latest version of this field's type signature at: https://docsmill.dev/npm/@keystatic/core@latest#/.fields.conditional