Skip to content

Custom multi-select example should use a JSON type field #1

@tkrotoff

Description

@tkrotoff

Instead of using a text field type and hacking value by transforming JSON into a string and vice-versa, use a JSON type field: https://payloadcms.com/docs/beta/fields/json



Example with a list of string:

import type { CollectionConfig } from "payload";

import { SelectCategories } from "./SelectCategories";

export const Banners: CollectionConfig = {
  slug: "banners",
  fields: [
    {
      name: "categories",
      type: "json",
      admin: { components: { Field: SelectCategories } },
      // The JSON Schema makes Payload generates the proper TypeScript types in payload-types.ts
      jsonSchema: {
        // Why? https://github.com/payloadcms/payload/issues/6737
        uri: "_",
        fileMatch: ["_"],
        schema: {
          type: "array",
          items: { type: "string" },
        },
      },
    },
  ],
};
"use client";

import { useField } from "@payloadcms/ui";

export function SelectCategories() {
  const { value, setValue } = useField<string[]>({});
  ...
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions