Command palette

@yasinsensoy/web

Web · Components

SchemaForm

Generates a form from a schema or JSON definition: fields, labels, required flags, validation, sections and steps in one component.

20 exports

Live example

Preview

PersonalYour contact details.
Account
Account type
Other

Code

import { SchemaForm } from "@yasinsensoy/web";

const Profile = z.object({
  name: z.string().min(2).meta({ title: "Full name" }),
  email: z.email().meta({ title: "Email" }),
  phone: z.string().meta({ title: "Phone", ui: { type: "phone" } }),
  type: z.enum(["personal", "business"]).meta({ title: "Account type" }),
  taxId: z.string().optional().meta({ title: "Tax ID" }),
  newsletter: z.boolean().describe("One email a month."),
  …
});

<SchemaForm schema={Profile} columns={2} resetLabel submitLabel="Kaydet"
  sections={[
    { title: "Personal", description: "Your contact details.", fields: ["name", "email", "phone", "country"] },
    { title: "Account", fields: ["type", { name: "taxId", when: { field: "type", equals: "business" } }, …] },
  ]}
  onValidSubmit={async (data) => save(data)} />

Events

  1. Events appear here when you interact with the preview.

Translation from a dictionary (switch language)

Your work address

Province
Account type

Without a schema, from a JSON definition

Import

import {
  SchemaForm,
  translateText,
  humanizeValue,
  localizeOptions,
  localizeField,
  localizeSection,
  humanizeName,
  deriveFromJsonSchema,
  deriveFields,
  isFieldVisible,
} from "@yasinsensoy/web";

SchemaForm

componentClient component

Generates a form from a schema or JSON definition: fields, labels, required flags, validation, sections and steps in one component. With a Zod schema, field types are derived from the schema; definitions can also come from the server as JSON.

  • Fields are the ready-made field components (TextField, SelectField, PhoneField…); validation, error display and mobile behavior are the same.
  • Types: text, email, password, url, textarea, number, select, multiselect, autocomplete, radio, checkbox, switch, date, datetime, daterange, time, file, slider, rating, tags, otp, color, richtext, phone, country, array, hidden. New types are added with components.
  • array: repeating rows (FieldArray); row fields via fields, with add/remove/drag to reorder built in.
  • Conditional field with when: { field: "type", equals: "business" }.
  • Titled sections with sections, a step-by-step wizard with steps.
  • Multiple columns with columns; one column on narrow screens.
  • draft, defaultValues, state, action, onValidSubmit are the same as in Form.

For derivation from the schema see deriveFields. Label via .meta({ title }), description via .describe(), field settings via .meta({ ui: { type: "textarea" } }), option names via .meta({ labels: { istanbul: "İstanbul" } }).

Translation: the label, description, placeholder, hint, option names, section/step titles and button texts are translated if they are a key in the dictionary (UIProvider messages) and update when the language changes (.meta({ title: "login.email" })); otherwise they are shown as is. An option without a name is generated from its value ("istanbul" → "İstanbul"). To translate a list from the dictionary use .meta({ ui: { optionsKey: "cities" } }) (cities.istanbul), and to translate the whole form from one root use i18nPrefix.

SchemaForm({ schema, fields: fieldList, sections, steps, columns, submitLabel, resetLabel, hideSubmit, components, children, wizard, i18nPrefix, defaultValues, onValidSubmit, ref, className, ...props }: SchemaFormProps<Schema>): JSX.Element

Examples

const Profile = z.object({
  name: z.string().min(2).meta({ title: "Full name" }),
  email: z.email(),
  phone: z.string().meta({ ui: { type: "phone" } }),
  role: z.enum(["admin", "editor", "reader"]),
  newsletter: z.boolean().describe("One email a month."),
});

<SchemaForm schema={Profile} columns={2} draft="profile"
  fields={["name", "email", "phone", { name: "role", span: "full" }, "newsletter"]}
  onValidSubmit={async (data) => save(data)} />

// From a JSON definition (no schema): validated with browser rules.
<SchemaForm action={formAction} state={state} fields={[
  { name: "type", type: "radio", label: "Account type", options: ["personal", "business"], required: true },
  { name: "taxId", label: "Tax ID", when: { field: "type", equals: "business" }, required: true },
]} />

// Step by step:
<SchemaForm schema={SignUp} draft="signup" steps={[
  { title: "Account", fields: ["email", "password"] },
  { title: "Address", fields: ["address.country", "address.city", "address.line"] },
]} onValidSubmit={signUp} />

Returns the translation if the text is a dictionary key, otherwise the text itself ("login.title" → "Sign in"; "Full name" → "Full name").

translateText(text: T, t: FormTranslator | undefined): T | string

Generates a readable label from an option value: "istanbul" → "Istanbul", "corporateAccount" → "Corporate account". Values starting with an uppercase letter ("TR") or containing digits or dots stay as they are.

humanizeValue(value: string): string

Display labels of options. Order: a label that is a dictionary key → prefix.field.options.value → optionsKey.value → label → label generated from the value.

localizeOptions(field: Pick<FormFieldConfig, "name" | "options" | "optionsKey">, t?: FormTranslator, { prefix }?: LocalizeOptions): Exclude<FormFieldOption, string>[] | undefined

Translates the texts of a field definition (label, description, tooltip, placeholder, options) from the dictionary. Text without a dictionary entry stays as is, so the schema can contain both plain text and keys.

localizeField(field: FormFieldConfig, t?: FormTranslator, options?: LocalizeOptions): FormFieldConfig

Examples

const t = await i18n.getT("en");
localizeField({ name: "city", label: "form.city", options: ["istanbul"] }, t);
// { name: "city", label: "City", options: [{ value: "istanbul", label: "Istanbul" }] }

Translates the title and description of a section or step.

localizeSection(section: S, t?: FormTranslator): S

humanizeName

function

Generates a label from a name: "birthDate" → "Birth date", "address.city" → "City".

humanizeName(name: string): string

Derives field definitions from a JSON Schema. Objects are flattened with parent.child names; property order is preserved.

deriveFromJsonSchema(schema: JsonSchema, root?: JsonSchema, prefix?: string): FormFieldConfig[]

deriveFields

function

Derives field definitions from a schema (one that offers Standard JSON Schema, such as Zod 4.2+). The label comes from title (.meta({ title })), the description from description (.describe()), field settings from .meta({ ui: { … } }).

Derivation rules:

  • string → text; email/url/date/time formats map to their own type; maxLength > 200 → textarea.
  • enum → radio with 3 or fewer options, otherwise select.
  • number → number (min/max); no decimals for integers.
  • boolean → checkbox; z.literal(true) is a required checkbox.
  • enum array → multiselect, string array → tags, object array → array (row fields in fields; add, remove, drag to reorder).
  • object → its fields named parent.child.
deriveFields(schema: StandardSchemaV1): FormFieldConfig[]

Examples

const Schema = z.object({
  name: z.string().min(2).meta({ title: "Full name" }),
  about: z.string().max(500).optional().meta({ ui: { type: "textarea", props: { rows: 4 } } }),
  role: z.enum(["admin", "editor", "reader"]),
});
deriveFields(Schema); // [{ name: "name", type: "text", label: "Full name", required: true, … }, …]

Does the field's condition match?

isFieldVisible(field: FormFieldConfig, values: Record<string, unknown>): boolean

Built-in field types.

type FormFieldType = "text" | "email" | "password" | "url" | "search" | "textarea" | "number" | "select" | "multiselect" | "autocomplete" | "radio" | "checkbox" | "switch" | "date" | "datetime" | "daterange" | "time" | "file" | "slider" | "rating" | "tags" | "otp" | "color" | "richtext" | "phone" | "country" | "array" | "hidden"

Translator: the result of useT or i18n.getT() (t and t.has).

NameTypeDescription
has(key: string): booleanWhether the key exists in the dictionary.

Translation options.

NameTypeDescription
prefix?stringDictionary root for field texts. With "forms.signup", these keys are looked up for the city field: - forms.signup.city (label when it is a string) or forms.signup.city.label - forms.signup.city.description, .placeholder, .tooltip - forms.signup.city.options.istanbul (option label)

Option: a string or { value, label }.

type FormFieldOption = string | { /** Submitted value. */ value: string; /** Display name. */ label?: string; /** Description shown below. */ description?: string; /** Not selectable. */ disabled?: boolean; }

Condition for showing the field (can be written as JSON). When several keys are given, all of them must match.

NameTypeDescription
fieldstringName of the field to look at.
equals?unknownVisible when the value equals this.
notEquals?unknownVisible when the value does not equal this.
in?readonly unknown[]Visible when the value is one of these.
filled?booleantrue: visible when the field is filled, false: when it is empty.

Definition of a single form field. Definitions without functions can be stored as JSON and sent from the server.

NameTypeDefaultDescription
namestringField name; may be nested ("address.city").
type?FormFieldType | (string & {})"text"Field type. Not needed when it can be derived from the schema.
label?stringLabel. Defaults to the schema's title or text generated from the name. If it is a dictionary key ("login.email") its translation is shown and updated when the language changes; otherwise it is shown as is.
description?stringHelp text. Defaults to the schema's description.
tooltip?stringⓘ tooltip next to the label.
placeholder?stringPlaceholder.
required?booleanRequired (asterisk on the label, browser validation).
disabled?booleanDisabled.
options?readonly FormFieldOption[]Options (select, multiselect, radio, autocomplete, tags). An option without a label gets one generated from its value ("newYork" → "New york"); a label that is a dictionary key is translated.
optionsKey?stringDictionary root for option labels: with "cities", the label of the istanbul option comes from the cities.istanbul key. Useful for translating the same list in many forms.
min?number | stringMinimum value (number, slider, date).
max?number | stringMaximum value.
step?numberStep.
minLength?numberMinimum characters.
maxLength?numberMaximum characters.
defaultValue?unknownInitial value (can also be given with Form defaultValues).
span?number | "full"1How many grid columns it spans (when columns > 1). "full" spans the row. On narrow screens every field is full width.
when?FormFieldCondition | readonly FormFieldCondition[] | ((values: Record<string, unknown>) => boolean)Visible (and submitted) only when the condition matches.
props?Record<string, unknown>Extra props passed as is to the field component (e.g. { rows: 5 }).
hidden?booleanHide (to not show a field coming from the schema).
fields?readonly FormFieldConfig[]Fields of a row for the array type; names are relative to the row ("name", "address.city"). Rows are added, removed and reordered by dragging with FieldArray (disable with props: { sortable: false }). min/max limit the row count. Derived automatically from an array of objects in the schema (z.array(z.object(...))).
columns?numberColumn count of the row fields for the array type (single column on narrow screens).

FormSection

interface

Field group: a titled section or a wizard step.

NameTypeDescription
title?stringSection title (step name in a wizard).
description?stringDescription.
fieldsreadonly (string | FormFieldConfig)[]Fields of the section: a name (from the schema) or a definition.
columns?numberColumn count in this section.
optional?booleanOptional step in a wizard (Skip button).

Field settings that can be written into the schema with .meta({ ui: … }).

type FormFieldMeta = Partial<Omit<FormFieldConfig, "name" | "when">>

Custom field renderer: takes the definition and returns the field.

type FormFieldRenderer = (field: FormFieldConfig & { label: string; }) => ReactNode

Props of the SchemaForm component.

Extends: Omit<FormProps<Schema>, "children">

NameTypeDefaultDescription
fields?readonly (string | FormFieldConfig)[]Fields and their order. If a name is given, the definition is derived from the schema; if a definition is given, it overrides what is derived from the schema ({ name: "role", type: "radio" }). If omitted, all fields in the schema are shown in order.
sections?readonly FormSection[]Splits the fields into titled sections (instead of fields).
steps?readonly FormSection[]Splits the fields into wizard steps: each step becomes a Wizard step, validated with the schema when moving forward. With draft, the current step is stored too.
columns?1 | 2 | 3 | 41Number of columns on wide screens; always one column on narrow screens.
i18nPrefix?stringDictionary root of the field texts. With "forms.signup", the label of the city field comes from forms.signup.city (or forms.signup.city.label), its description from forms.signup.city.description, and its options from forms.signup.city.options.<value>. For a missing key the text in the schema is used.
submitLabel?ReactNode"Gönder"Text of the submit button (can be a dictionary key).
resetLabel?ReactNode | trueReset button: true with the default text, or with the given text.
hideSubmit?booleanHide the submit button (if you put your own button with children).
components?Partial<Record<string, FormFieldRenderer>>Custom field renderers by type. To replace a built-in type or add a new one ({ iban: (f) => <TextField {...f} mask="iban" /> }).
children?ReactNodeShown after the fields, before the buttons.
wizard?Omit<WizardProps<Schema>, "steps" | "schema" | "onComplete" | "defaultValues" | "draft" | "action" | "state">Extra props passed to Wizard when the wizard is used.