Custom Templates
This is an advanced feature that lets you customize even more aspects of the form:
| Custom Field | Custom Template | Custom Widget | |
|---|---|---|---|
| What it does | Overrides all behaviour | Overrides just the layout (not behaviour) | Overrides just the input box (not layout, labels, or help, or validation) |
| Usage | Global or per-field | Global or per-field | Global or per-field |
| Global Example | <Form fields={{ MyCustomField }} /> | <Form templates={{ ArrayFieldTemplate: MyArrayTemplate }} /> | <Form widgets={{ MyCustomWidget }} /> |
| Per-Field Example | "ui:field": MyCustomField | "ui:ArrayFieldTemplate": MyArrayTemplate | "ui:widget":MyCustomWidget |
| Documentation | Custom Fields | See documentation below | Custom Widgets |
To understand how Fields, Templates, and Widgets work together, consider how a room is built and furnished:
- 👷 Custom Field (General Contractor / Room Architect): Oversees the entire room. Dictates end-to-end logic and coordinates any sub-fields, as the built-in
ObjectFieldandArrayFielddo. - 📐 Custom Template (Framing & Layout): The structural scaffolding. Determines where elements sit relative to each other—arranging titles, descriptions, error banners, and the input slot. It doesn't care what the input control looks like.
- 🎛️ Custom Widget (Fixture / Appliance): The interactive leaf control the user actually touches—the light switch, faucet, text input, toggle, or date picker. It only takes a value and fires change, focus and blur events.
In version 5, all existing templates were consolidated into a new TemplatesType interface that is provided as part of the Registry.
They can also be overloaded globally on the Form via the templates prop as well as per-field through the uiSchema.
Further, many new templates were added or repurposed from existing widgets and fields in an effort to simplify the effort needed by theme authors to build new and/or maintain current themes.
These new templates can also be overridden by individual users to customize the specific needs of their application.
A special category of templates, ButtonTemplates, were also added to support the easy replacement of the Submit button on the form, the Add and Remove buttons associated with additionalProperties and patternProperties on objects and elements of arrays, the Move up and Move down buttons used for reordering arrays, and the Copy button that duplicates an array item.
Version 6 added the Clear button that empties a text input.
This category, unlike the others, can only be overridden globally via the templates prop on Form.
Below is the table that lists all the templates, their props interface, their uiSchema name and from where they originated in the previous version of RJSF:
| Template | Props Type | UiSchema name | Origin |
|---|---|---|---|
| ArrayFieldTemplate | ArrayFieldTemplateProps | ui:ArrayFieldTemplate | Formerly Form.ArrayFieldTemplate or Registry.ArrayFieldTemplate |
| ArrayFieldDescriptionTemplate | ArrayFieldDescriptionProps | ui:ArrayFieldDescriptionTemplate | Formerly part of @rjsf/core ArrayField, refactored as a template, used in all ArrayFieldTemplate implementations |
| ArrayFieldItemTemplate | ArrayFieldItemTemplateProps | ui:ArrayFieldItemTemplate | Formerly an internal class for ArrayFieldTemplates in all themes, refactored as a template in each theme, used in all ArrayFieldTemplate implementations |
| ArrayFieldItemButtonsTemplate | ArrayFieldItemButtonsTemplateProps | ui:ArrayFieldItemButtonsTemplate | Formerly an internal class for ArrayFieldItemTemplates in all themes, refactored as a template in the core, used in all ArrayFieldItemTemplate implementations |
| ArrayFieldTitleTemplate | ArrayFieldTitleProps | ui:ArrayFieldTitleTemplate | Formerly part of @rjsf/core ArrayField, refactored as a template, used in all ArrayFieldTemplate implementations. |
| BaseInputTemplate | WidgetProps | ui:BaseInputTemplate | Formerly a widget in @rjsf.core moved to templates and newly implemented in each theme to maximize code reuse. |
| CyclicSchemaExpandTemplate | CyclicSchemaExpandProps | ui:CyclicSchemaExpandTemplate | Added in RJSF v6 to support circular $ref cycle detection |
| DescriptionFieldTemplate | DescriptionFieldProps | ui:DescriptionFieldTemplate | Formerly a field in @rjsf.core moved to templates with the Template suffix. Previously implemented in each theme. |
| ErrorListTemplate | ErrorListProps | ui:ErrorListTemplate | Formerly Form.ErrorList moved to templates with the Templates suffix. Previously implemented in each theme. |
| FallbackFieldTemplate | FallbackFieldTemplateProps | ui:FallbackFieldTemplate | Added in RJSF v6 |
| FieldErrorTemplate | FieldErrorProps | ui:FieldErrorTemplate | Formerly internal ErrorList component accessible only to SchemaField |
| FieldHelpTemplate | FieldHelpProps | ui:FieldHelpTemplate | Formerly internal Help component accessible only to SchemaField |
| FieldTemplate | FieldTemplateProps | ui:FieldTemplate | Formerly Form.FieldTemplate or Registry.FieldTemplate |
| GridTemplate | GridTemplateProps | ui:GridTemplate | Theme dependent implementations of a Grid element for either rows or columns |
| MarkdownTemplate | MarkdownTemplateProps | ui:MarkdownTemplate | Added in RJSF v7 to make markdown rendering opt-in |
| MultiSchemaFieldTemplate | MultiSchemaFieldTemplateProps | ui:MultiSchemaFieldTemplate | Formerly part of @rjsf/core MultiSchemaField`, refactored as a template |
| ObjectFieldTemplate | ObjectFieldTemplateProps | ui:ObjectFieldTemplate | Formerly Form.ObjectFieldTemplate or Registry.ObjectFieldTemplate |
| OptionalDataControlsTemplate | OptionalDataControlsTemplateProps | ui:OptionalDataControlsTemplate | New feature in V6 |
| TitleFieldTemplate | TitleFieldProps | ui:TitleFieldTemplate | Formerly a field in @rjsf.core moved to templates with the Template suffix. Previously implemented in each theme. |
| UnsupportedFieldTemplate | UnsupportedFieldProps | ui:UnsupportedFieldTemplate | Formerly a field in @rjsf.core moved to templates with the Template suffix. |
| WrapIfAdditionalTemplate | WrapIfAdditionalTemplateProps | ui:WrapIfAdditionalTemplate | Formerly an internal component in @rjsf.core. Previously implemented in most themes. |
| ButtonTemplates.AddButton | IconButtonProps | n/a | Formerly an internal implementation in each theme |
| ButtonTemplates.ClearButton | IconButtonProps | n/a | Added in RJSF v6 |
| ButtonTemplates.CopyButton | IconButtonProps | n/a | Added in RJSF v5 |
| ButtonTemplates.MoveDownButton | IconButtonProps | n/a | Formerly an internal implementation in each theme |
| ButtonTemplates.MoveUpButton | IconButtonProps | n/a | Formerly an internal implementation in each theme |
| ButtonTemplates.RemoveButton | IconButtonProps | n/a | Formerly an internal implementation in each theme |
| ButtonTemplates.SubmitButton | SubmitButtonProps | n/a | Formerly a field in each theme move to templates.ButtonTemplates |
ArrayFieldTemplate
You can use an ArrayFieldTemplate to customize how your arrays are rendered.
This allows you to customize your array, and each element in the array.
If you only want to customize how the array's title, description or how the array items are presented, you may want to consider providing your own ArrayFieldDescriptionTemplate, ArrayFieldItemTemplate and/or ArrayFieldTitleTemplate instead.
You can also customize arrays by specifying a widget in the relevant ui:widget schema, more details over on Custom Widgets.
import { ArrayFieldTemplateProps, RJSFSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'array',
items: {
type: 'string',
},
};
function ArrayFieldTemplate(props: ArrayFieldTemplateProps) {
return (
<div>
{props.items}
{props.canAdd && (
<button type='button' onClick={props.onAddClick} disabled={props.disabled || props.readonly}>
Add
</button>
)}
</div>
);
}
render(
<Form schema={schema} validator={validator} templates={{ ArrayFieldTemplate }} />,
document.getElementById('app'),
);
You also can provide your own field template to a uiSchema by specifying a ui:ArrayFieldTemplate property with your Component :
import { UiSchema } from '@rjsf/utils';
import ArrayFieldTemplate from './ArrayFieldTemplate';
const uiSchema: UiSchema = {
'ui:ArrayFieldTemplate': ArrayFieldTemplate,
};
or a string value from the Registry :
import { UiSchema } from '@rjsf/utils';
const uiSchema: UiSchema = {
'ui:ArrayFieldTemplate': 'CustomArrayFieldTemplate',
};
Please see the customArray.tsx sample from the playground for another example.
The following props are passed to each ArrayFieldTemplate:
canAdd: A boolean value stating whether the array has room for a new item and its options allow one. It is false for an optional array without data, whose data itsoptionalDataControlstarts, andonAddClickdoes nothing there. It doesn't coverdisabledorreadonly, under whichonAddClickdoes nothing, so an add button drawn from it has to be disabled ondisabled || readonlytoo.className: The className string.disabled: A boolean value stating if the array is disabled.id: The id of the field in the hierarchy.items: An array of React nodes representing the items in the array.onAddClick: (event?: SyntheticEvent<HTMLElement>) => void: A function that adds a new item to the end of the array. It does nothing where the array's add button can't act, such as on a disabled array.readonly: A boolean value stating if the array is read-only.required: A boolean value stating if the array's heading carries the required marker: where the array is required, unless a field above rendering the same id draws the marked label, as ananyOf/oneOffield does for its option.hideError: A boolean value stating if the field is hiding its errors.schema: The schema object for this array.uiSchema: The uiSchema object for this array field.title: A string value containing the title for the array.optionalDataControl: The control that adds or removes the data of an optional array, when it has one.titleDrawsOptionalDataControl()says whether to lay it out in the heading drawn fortitleor with the items, so it isn't dropped with a heading that isn't drawn.presentation: The array's plan: whether its heading and description are this template's to draw, which they aren't when they repeat the field above it, and the id its description renders under. It also carries the array's own errors,presentation.errors.messages, withui:hideErrorapplied, which this template draws, underpresentation.errors.id, only wherepresentation.errors.byis'self'; under'template'theFieldTemplatedraws them.getErrorsToDraw()gives the messages this template draws. SeeresolveFieldPresentation().getArrayDescription()reads the description this template draws from it, falling back to theui:descriptionor schemadescriptionfor a template rendered without one.formData: The formData for this array.errorSchema: The optional validation errors for the array field and the items within it, in the form of anErrorSchemahasErrors: Whether the array shows its own errors, asui:hideErrorleaves them. Beneath ananyOf/oneOffield it can differ frompresentation.errors.messages, which are the field above's where that field shows them. An array rendered besideanyOf/oneOfoptions of its own leaves its errors to the selected option, so it isfalsethere.rawErrors: An array of strings listing the array's own errors, whicherrorSchemadoesn't hold. Unlike therawErrorsaFieldTemplatereceives, it carries them whateverhideErrorsays. Deprecated, and kept through v7 for a template rendered without a plan: readgetErrorsToDraw()for the messages this template draws itself,presentation.errors.messages, withui:hideErrorapplied, wherepresentation.errors.byis'self', since theFieldTemplatedraws them under'template', andhasErrorsfor an error state, instead.getErrorsToDraw()falls back torawErrorswithhideErrorwithout a plan.registry: Theregistryobject.
Note: Array and object field templates are always rendered inside the FieldTemplate. To fully customize an array field template, you may need to specify both
ui:FieldTemplateandui:ArrayFieldTemplate.
ArrayFieldDescriptionTemplate
The out-of-the-box version of this template will render the DescriptionFieldTemplate with a generated id, if there is a description otherwise nothing is rendered.
If you want different behavior for the rendering of the description of an array field, you can customize this template.
If you want a different behavior for the rendering of ALL descriptions in the Form, see DescriptionFieldTemplate
import { ArrayFieldDescriptionProps, RJSFSchema, descriptionId } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'array',
items: {
type: 'string',
},
};
function ArrayFieldDescriptionTemplate(props: ArrayFieldDescriptionProps) {
const { description, id } = props;
return (
<details id={descriptionId(id)}>
<summary>Description</summary>
{description}
</details>
);
}
render(
<Form schema={schema} validator={validator} templates={{ ArrayFieldDescriptionTemplate }} />,
document.getElementById('app'),
);
You also can provide your own field template to a uiSchema by specifying a ui:ArrayFieldDescriptionTemplate property with your Component :
import { UiSchema } from '@rjsf/utils';
import ArrayFieldDescriptionTemplate from './ArrayFieldDescriptionTemplate';
const uiSchema: UiSchema = {
'ui:ArrayFieldDescriptionTemplate': ArrayFieldDescriptionTemplate,
};
or a string value from the Registry :
import { UiSchema } from '@rjsf/utils';
const uiSchema: UiSchema = {
'ui:ArrayFieldDescriptionTemplate': 'CustomArrayFieldDescriptionTemplate',
};
The following props are passed to each ArrayFieldDescriptionTemplate:
description: The description of the array field being rendered.id: The id of the field in the hierarchy.presentation: The array's plan, whose description id the description renders under when there is one.schema: The schema object for this array field.uiSchema: The uiSchema object for this array field.registry: Theregistryobject.
ArrayFieldItemTemplate
The ArrayFieldItemTemplate is used to render the representation of a single item in an array.
All of the ArrayFieldTemplate implementations in all themes get this template from the registry in order to render array fields items.
Each theme has an implementation of the ArrayFieldItemTemplate to render an array field item in a manner best suited to the theme.
If you want to change how an array field item is rendered you can customize this template (for instance to remove the buttons rendered by ArrayFieldItemButtonsTemplate).
import { ArrayFieldItemTemplateProps, RJSFSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'array',
items: {
type: 'string',
},
};
function ArrayFieldItemTemplate(props: ArrayFieldItemTemplateProps) {
const { children, className } = props;
return <div className={className}>{children}</div>;
}
render(
<Form schema={schema} validator={validator} templates={{ ArrayFieldItemTemplate }} />,
document.getElementById('app'),
);
The following props are passed to each ArrayFieldItemTemplate:
children: The html for the item's content.buttonsProps: The props to pass to theArrayFieldItemButtonsTemplate.className: The className string.disabled: Whether the array item's buttons are disabled, by the array's lock or the item's own. Its inputs can stay enabled, under an item'sui:disabled: false.hasToolbar: A boolean value stating whether the array item has a toolbar.index: A number stating the index the array item occurs initems.totalItems: A number stating the total numberitemsin the array.itemKey: A stable, unique key for the array item.readonly: Whether the array item's buttons are read-only, by the array's lock or the item's own. Its inputs can stay editable, under an item'sui:readonly: false.schema: The schema object for this array item.uiSchema: The uiSchema object for this array item.registry: Theregistryobject.parentUiSchema: The UI schema of the array item's parent array field, used for customization in some themesdisplayLabel: Whether a label sits above the item's control: one the item'sFieldTemplatedraws, as the planSchemaFieldbuilds for the item says, which is thedisplayLabelthat template is handed, or one the item's field or widget draws itself where its theme declares itlabelPlacement: 'above', as a theme whose widgets draw their own label above the control does. Used to place the item's buttons beside its control rather than beside its label.
ArrayFieldItemButtonsTemplate
The ArrayFieldItemButtonsTemplate is used to render the representation of the buttons used for copying, moving and deleting an item in an array.
All of the ArrayFieldItemTemplate implementations in all themes get this template from the registry in order to render array fields items' buttons.
Most themes use the core implementation of this template, since the button rendering is identical across them; @rjsf/daisyui provides its own.
If you want to change how an array field item's buttons are rendered you can customize this template (for instance to remove the move up/down and remove buttons).
import { ArrayFieldItemButtonsTemplateProps, buttonId, RJSFSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'array',
items: {
type: 'string',
},
};
function ArrayFieldItemButtonsTemplate(props: ArrayFieldItemButtonsTemplateProps) {
const { disabled, readonly, hasCopy, id, onCopyItem, registry, uiSchema } = props;
const { CopyButton } = registry.templates.ButtonTemplates;
if (!hasCopy) {
return undefined;
}
return (
<CopyButton
id={buttonId(id, 'copy')}
className='array-item-copy'
disabled={disabled || readonly}
onClick={onCopyItem}
uiSchema={uiSchema}
registry={registry}
/>
);
}
render(
<Form schema={schema} validator={validator} templates={{ ArrayFieldItemButtonsTemplate }} />,
document.getElementById('app'),
);
The following props are passed to each ArrayFieldItemButtonsTemplate:
className: The className string.disabled: Whether the array item's buttons are disabled, by the array's lock or the item's own. Its inputs can stay enabled, under an item'sui:disabled: false.canAdd: A boolean value stating whether a new item can be added below this one, which is whenonAddItemacts. It is false on a disabled or read-only array.hasCopy: A boolean value stating whether the array item can be copied.hasMoveDown: A boolean value stating whether the array item can be moved down.hasMoveUp: A boolean value stating whether the array item can be moved up.hasRemove: A boolean value stating whether the array item can be removed.id: The id of the field in the hierarchy.index: A number stating the index the array item occurs initems.totalItems: A number stating the total numberitemsin the array.onAddItem: (event?: SyntheticEvent<HTMLElement>) => void: Callback function that adds a new item below this item, or does nothing where its button can't act.onCopyItem: (event?: SyntheticEvent<HTMLElement>) => void: Callback function that copies this item below itself, or does nothing where its button can't act.onRemoveItem: (event?: SyntheticEvent<HTMLElement>) => void: Callback function that removes the item from the list, or does nothing where its button can't act, such as underui:removable: falseor on a disabled array.onMoveUpItem: (event?: SyntheticEvent<HTMLElement>) => void: Callback function that moves the item up one spot in the list, or does nothing where its button can't act.onMoveDownItem: (event?: SyntheticEvent<HTMLElement>) => void: Callback function that moves the item down one spot in the list, or does nothing where its button can't act.readonly: Whether the array item's buttons are read-only, by the array's lock or the item's own. Its inputs can stay editable, under an item'sui:readonly: false.itemButtonProps: Props to spread onto each of the item's buttons, keyed bycopy,moveDown,moveUpandremove, with a key only for the buttons the item can show. Set when the array'sitemLabeloption names the item, to title the buttons after it, such asRemove report.pdf; otherwise undefined. A template that renders its own buttons can spread them too, as in<button {...itemButtonProps?.remove} onClick={onRemoveItem}>.schema: The schema object for this array item.style: The optional style to pass to all of the buttonsuiSchema: The uiSchema object for this array item.registry: Theregistryobject.
ArrayFieldTitleTemplate
The out-of-the-box version of this template will render the TitleFieldTemplate with a generated id, if there is a title otherwise nothing is rendered.
If you want a different behavior for the rendering of the title of an array field, you can customize this template.
If you want a different behavior for the rendering of ALL titles in the Form, see TitleFieldTemplate
import { ArrayFieldTitleProps, RJSFSchema, titleId } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'array',
items: {
type: 'string',
},
};
function ArrayFieldTitleTemplate(props: ArrayFieldTitleProps) {
const { title, id } = props;
return <h1 id={titleId(id)}>{title}</h1>;
}
render(
<Form schema={schema} validator={validator} templates={{ ArrayFieldTitleTemplate }} />,
document.getElementById('app'),
);
You also can provide your own template to a uiSchema by specifying a ui:ArrayFieldTitleTemplate property with your Component :
import { UiSchema } from '@rjsf/utils';
import ArrayFieldTitleTemplate from './ArrayFieldTitleTemplate';
const uiSchema: UiSchema = {
'ui:ArrayFieldTitleTemplate': ArrayFieldTitleTemplate,
};
or a string value from the Registry :
import { UiSchema } from '@rjsf/utils';
const uiSchema: UiSchema = {
'ui:ArrayFieldTitleTemplate': 'CustomArrayFieldTitleTemplate',
};
The following props are passed to each ArrayFieldTitleTemplate:
title: The title of the array field being rendered.id: The id of the field in the hierarchy.schema: The schema object for this array field.uiSchema: The uiSchema object for this array field.required: A boolean value stating if the field is requiredregistry: Theregistryobject.
BaseInputTemplate
The BaseInputTemplate is the template to use to render the basic <input> component for a theme.
It is used as the template for rendering many of the <input> based widgets that differ by type and callbacks only.
For example, the TextWidget implementation in core is simply a wrapper around BaseInputTemplate that it gets from the registry.
Additionally, each theme implements its own version of BaseInputTemplate without needing to provide a different implementation of TextWidget.
If you desire a different implementation for the <input> based widgets, you can customize this template.
For instance, say you have a CustomTextInput component that you want to integrate:
import { ChangeEvent, FocusEvent } from 'react';
import {
BaseInputTemplateProps,
getBaseInputProps,
getControlAttributes,
hasWidgetErrors,
RJSFSchema,
toInputValue,
} from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
import CustomTextInput from '../CustomTextInput';
const schema: RJSFSchema = {
type: 'string',
title: 'My input',
description: 'input description',
};
function BaseInputTemplate(props: BaseInputTemplateProps) {
const {
schema,
id,
options,
label,
value,
type,
placeholder,
required,
disabled,
readonly,
autofocus,
onChange,
onChangeOverride,
onBlur,
onFocus,
rawErrors,
hideError,
presentation,
uiSchema,
registry,
...rest
} = props;
const onTextChange = ({ target: { value: val } }: ChangeEvent<HTMLInputElement>) => {
// Use the options.emptyValue if it is specified and newVal is also an empty string
onChange(val === '' ? options.emptyValue || '' : val);
};
const onTextBlur = ({ target: { value: val } }: FocusEvent<HTMLInputElement>) => onBlur(id, val);
const onTextFocus = ({ target: { value: val } }: FocusEvent<HTMLInputElement>) => onFocus(id, val);
const { title, ...baseInputProps } = getBaseInputProps(props);
const inputProps = { ...rest, ...baseInputProps };
// The field's plan leaves out the errors `ui:hideError` hides, and `hasWidgetErrors()` reads the `aria-invalid` it
// gives the control, falling back to `rawErrors` with `hideError` for a widget rendered without a plan. The messages
// are drawn here only where the plan has the widget draw them, under the id the control's `aria-describedby` names,
// and by the `FieldTemplate` otherwise. `rawErrors`, `hideError` and `presentation` stay destructured so that
// `...rest` does not spread them onto the input
const hasError = hasWidgetErrors(props);
const ownErrors = presentation?.errors.by === 'self' ? presentation.errors : undefined;
return (
<>
<CustomTextInput
id={id}
label={label}
value={toInputValue(value)}
placeholder={placeholder}
disabled={disabled}
readOnly={readonly}
autoFocus={autofocus}
error={hasError}
onChange={onChangeOverride || onTextChange}
onBlur={onTextBlur}
onFocus={onTextFocus}
title={title}
{...inputProps}
{...getControlAttributes({ id, presentation })}
/>
{ownErrors && (
<ul id={ownErrors.id}>
{ownErrors.messages.map((error) => (
<li key={error}>{error}</li>
))}
</ul>
)}
</>
);
}
render(
<Form schema={schema} validator={validator} templates={{ BaseInputTemplate }} />,
document.getElementById('app'),
);
Wrapping BaseInputTemplate to customize it
Sometimes you just need to pass some additional properties to the existing BaseInputTemplate.
The way to do this varies based upon whether you are using core or some other theme (such as mui):
import { BaseInputTemplateProps } from '@rjsf/utils';
import { BaseInputTemplate } from '@rjsf/core'; // or from a theme: `const { BaseInputTemplate } = Templates` with `import { Templates } from '@rjsf/mui'`
function MyBaseInputTemplate(props: BaseInputTemplateProps) {
const customProps = {};
// get your custom props from where you need to
return <BaseInputTemplate {...props} {...customProps} />;
}
The following props are passed to the BaseInputTemplate:
id: The generated id for this widget;schema: The JSONSchema subschema object for this widget;uiSchema: The uiSchema for this widget;value: The current value for this widget;placeholder: The placeholder for the widget, if any;required: The required status of this widget's control. A label the widget draws is marked fromtemplateMarksRequired(), since the selector of a requiredanyOf/oneOffield marks its label without being required, and the control of its selected option is required beneath an unmarked label;disabled: A boolean value stating if the widget is disabled;hideError: A boolean value stating if the widget is hiding its errors.readonly: A boolean value stating if the widget is read-only;autofocus: A boolean value stating if the widget should autofocus;label: The computed label for this widget, as a stringmultiple: A boolean value stating if the widget can accept multiple values.ArrayFieldpasses it to the widget of any multi-select, sogetBaseInputProps()puts it only on afileinput;type: Thetypeof the input, which the widgets rendering aBaseInputTemplateset, such as'number'or'date';pattern: Apatterna widget passes for the input, which replaces the one the schema derives.getBaseInputProps()puts it,inputModeandacceptover the input props derived from the schema and addsmultipleto afileinput, andcallerInputProps()returns those three on their own. Apatterncounts even when it is undefined, which turns the derived one off;inputMode: AninputModea widget passes for the input, which replaces the one the schema derives, and whichcallerInputProps()returns the way it returnspattern;accept: The file types a widget passes for the input, which replaceui:options.accept, and whichcallerInputProps()returns too;onChange: The value change event handler; call it with the new value every time it changes;onChangeOverride: ABaseInputTemplateimplements a defaultonChangehandler that it passes to the HTML input component to handle theChangeEvent. Sometimes a widget may need to handle theChangeEventusing custom logic. If that is the case, that widget should provide its own handler via this prop;onBlur: The input blur event handler; call it with the widget id and value;onFocus: The input focus event handler; call it with the widget id and value;options: A map of options passed as a prop to the component (see Custom widget options).options.enumOptions: For enum fields, this property contains the list of options for the enum as an array of { label, value } objects. If the enum is defined using the oneOf/anyOf syntax, the entire schema object for each option is appended onto the { schema, label, value } object.rawErrors: An array of strings listing all generated error messages from encountered errors for this widget. It carries them whateverhideErrorsays. Deprecated, and kept through v7 for a widget rendered without a plan: readhasWidgetErrors(), which follows thearia-invalidthe plan givespresentation.control, for the widget's error state instead;presentation: The plan of the field the widget renders the value of: the errors it shows,presentation.errors.messages, withui:hideErrorapplied, whether the widget draws them itself,presentation.errors.by === 'self', and the attributes its control carries, whichgetControlAttributes()gives it. Undefined for a widget rendered without aSchemaFieldabove it, or by a field that draws its parts itself.registry: Theregistryobject
CyclicSchemaExpandTemplate
The CyclicSchemaExpandTemplate is the template rendered by CyclicSchemaField when a circular $ref cycle is detected in the schema.
RJSF automatically detects when a $ref would recurse indefinitely (e.g. a schema whose property references its own root) and stops rendering at the cycle boundary.
At that point CyclicSchemaField renders this template, which shows a warning message and an expand button that the user can click to render one additional level of the recursive structure.
Which fields are expanded is the form's state, by field path, so an expansion survives the field unmounting and mounting again and follows the moves the form makes, of array items and of additional properties renamed or removed; CyclicSchemaField renders an expanded field from expandRefCycle().
When the field one level further would render hidden, through ui:widget: 'hidden' or a deprecatedHandling of 'hide', there is nothing to expand to, so CyclicSchemaField renders nothing in place of this template.
Only an object's property is collapsed into a cycle, and ObjectField marks such a property hidden for its ObjectFieldTemplate; an array's items are resolved for each item's data, which ends the recursion, so an array row is never a cycle and a hidden one renders as any hidden item does.
Each theme provides its own implementation.
You can replace the template globally via the templates prop on Form, or per-field via ui:CyclicSchemaExpandTemplate in the uiSchema.
import { CyclicSchemaExpandProps, expandButtonId, RJSFSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
// A schema that is self-referencing
const schema: RJSFSchema = {
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'object',
title: 'Node',
properties: {
value: { type: 'string' },
child: { $ref: '#' },
},
};
function CyclicSchemaExpandTemplate<T = unknown>(props: CyclicSchemaExpandProps<T>) {
const { name, id, onExpand } = props;
const buttonId = expandButtonId(id);
return (
<div className='cyclic-expand'>
<span className='warning'>Circular reference detected for field "{name}"</span>
<button id={buttonId} type='button' onClick={() => onExpand(id)}>
Expand
</button>
</div>
);
}
render(
<Form schema={schema} validator={validator} templates={{ CyclicSchemaExpandTemplate }} />,
document.getElementById('app'),
);
You can also provide a per-field template via uiSchema:
import { UiSchema } from '@rjsf/utils';
import CyclicSchemaExpandTemplate from './CyclicSchemaExpandTemplate';
const uiSchema: UiSchema = {
'ui:CyclicSchemaExpandTemplate': CyclicSchemaExpandTemplate,
};
or a string value from the Registry:
import { UiSchema } from '@rjsf/utils';
const uiSchema: UiSchema = {
'ui:CyclicSchemaExpandTemplate': 'CustomCyclicSchemaExpandTemplate',
};
The following props are passed to the CyclicSchemaExpandTemplate as defined by CyclicSchemaExpandProps in @rjsf/utils:
name: The unique name of the field at the cycle boundary, usually the property name within its parent object.id: The id of the field in the hierarchy.onExpand: Callback to call when the user wants to render one additional level; receives the field's id string.schema: The schema object for the field at the cycle boundary.uiSchema: The uiSchema object for this field.registry: Theregistryobject.
DescriptionFieldTemplate
Each theme implements a DescriptionFieldTemplate used to render the description of a field.
If you want to customize how descriptions are rendered you can.
import { DescriptionFieldProps, RJSFSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'string',
title: 'My input',
description: 'input description',
};
function DescriptionFieldTemplate(props: DescriptionFieldProps) {
const { description, id } = props;
return (
<details id={id}>
<summary>Description</summary>
{description}
</details>
);
}
render(
<Form schema={schema} validator={validator} templates={{ DescriptionFieldTemplate }} />,
document.getElementById('app'),
);
The following props are passed to the DescriptionFieldTemplate:
description: The description of the field being rendered.id: The id of the field in the hierarchy.hasErrors: Whether the field it describes shows its own errors, asui:hideErrorleaves them. Core's template marks itselfdata-invalidwhile it is set.schema: The schema object for the field.uiSchema: The uiSchema object for the field.registry: Theregistryobject.
ErrorListTemplate
The ErrorListTemplate is the template that renders the all the errors associated with the fields in the Form, at the top.
Each theme implements a ErrorListTemplate used to render its errors using components for the theme's toolkit.
If you want to customize how all the errors are rendered you can.
import { ErrorListProps, RJSFValidationError, RJSFSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'string',
title: 'My input',
description: 'input description',
};
function ErrorListTemplate(props: ErrorListProps) {
const { errors } = props;
return (
<details id={id}>
<summary>Errors</summary>
<ul>
{errors.map((error: RJSFValidationError, i: number) => {
return (
<li key={i} className='error'>
{error.stack}
</li>
);
})}
</ul>
</details>
);
}
render(
<Form schema={schema} validator={validator} templates={{ ErrorListTemplate }} />,
document.getElementById('app'),
);
The following props are passed to the ErrorListTemplate:
schema: The schema that was passed toFormuiSchema: The uiSchema that was passed toFormerrors: An array of all errors in thisForm.errorSchema: TheErrorSchemaconstructed byForm
FallbackFieldTemplate
The FallbackFieldTemplate is the template that renders opt-in fallback UI to control fields of unknown or unhandled types. Usage of this feature is controlled by the useFallbackUiForUnsupportedType Form prop.
import { FallbackFieldTemplateProps, RJSFSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'unknownType',
title: 'My input',
};
function FallbackFieldTemplate(props: FallbackFieldTemplateProps) {
const { typeSelector, schemaField } = props;
return (
<div className={'row'}>
<div className={'col-xs-4'}>{typeSelector}</div>
<div className={'col-xs-8'}>{schemaField}</div>
</div>
);
}
render(
<Form schema={schema} validator={validator} templates={{ FallbackFieldTemplate }} />,
document.getElementById('app'),
);
The following props are passed to the FallbackFieldTemplate:
schema: The schema for the fielduiSchema: The uiSchema for the fieldregistry: TheRegistryobject 1
FieldErrorTemplate
The FieldErrorTemplate is the template that renders all the errors associated a single field.
If you want to customize how the errors are rendered you can.
import { FieldErrorProps, RJSFSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'string',
title: 'My input',
description: 'input description',
};
function FieldErrorTemplate(props: FieldErrorProps) {
const { errors } = props;
return (
<details id={id}>
<summary>Errors</summary>
<ul>
{errors.map((error: string, i: number) => {
return (
<li key={i} className='error'>
{error.stack}
</li>
);
})}
</ul>
</details>
);
}
render(
<Form schema={schema} validator={validator} templates={{ FieldErrorTemplate }} />,
document.getElementById('app'),
);
The following props are passed to the FieldErrorTemplate:
schema: The schema for the fielduiSchema: The uiSchema for the fieldid: The id of the field in the hierarchy.errors: An array of all errors for this fielderrorSchema: TheErrorSchemafor this fieldregistry: TheRegistryobject
FieldHelpTemplate
The FieldHelpTemplate is the template that renders the help associated a single field.
If you want to customize how the help is rendered you can.
import { FieldHelpProps, RJSFSchema, helpId } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'string',
title: 'My input',
description: 'input description',
};
function FieldHelpTemplate(props: FieldHelpProps) {
const { help, id, presentation } = props;
return <aside id={presentation?.help.id ?? helpId(id)}>{help}</aside>;
}
render(
<Form schema={schema} validator={validator} templates={{ FieldHelpTemplate }} />,
document.getElementById('app'),
);
The following props are passed to the FieldHelpTemplate:
schema: The schema for the fielduiSchema: The uiSchema for the fieldid: The id of the field in the hierarchy.help: The help information to be renderedhasErrors: Whether the field has errors to showregistry: TheRegistryobjectpresentation: The field's plan, whose help id the help renders under when there is one. AnanyOf/oneOfoption showing help of its own beneath its field's takesoptionHelpId(), so it doesn't repeat the field'shelpId(id).
FieldTemplate
To take control over the inner organization of each field (each form row), you can define a field template for your form.
A field template is basically a React stateless component being passed field-related props, allowing you to structure your form row as you like.
To keep an array item's buttons and an additional property's key input level with the field's control, see Lining up a custom FieldTemplate.
import { FieldTemplateProps, RJSFSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'string',
};
function CustomFieldTemplate(props: FieldTemplateProps) {
const { id, classNames, style, label, help, required, description, errors, children, presentation } = props;
return (
<div className={classNames} style={style}>
<label htmlFor={id}>
<span id={presentation?.label.id}>{label}</span>
{required ? '*' : null}
</label>
{description}
{children}
{errors}
{help}
</div>
);
}
render(
<Form schema={schema} validator={validator} templates={{ FieldTemplate: CustomFieldTemplate }} />,
document.getElementById('app'),
);
You also can provide your own field template to a uiSchema by specifying a ui:FieldTemplate property with your Component :
import { UiSchema } from '@rjsf/utils';
import CustomFieldTemplate from './CustomFieldTemplate';
const uiSchema: UiSchema = {
'ui:FieldTemplate': CustomFieldTemplate,
};
or a string value from the Registry :
import { UiSchema } from '@rjsf/utils';
const uiSchema: UiSchema = {
'ui:FieldTemplate': 'CustomFieldTemplate',
};
If you want to handle the rendering of each element yourself, you can use the props rawHelp, rawDescription and rawErrors. rawErrors holds only the errors the field is displaying, so it is undefined while ui:hideError is in effect; read errorSchema instead to render the withheld errors your own way.
The following props are passed to a custom field template component:
fieldPath: TheFieldPathstring identifying where this field's data lives, such asfriends[0].firstName.id: The id of the field in the hierarchy. You can use it to render a label targeting the wrapped widget, as theforthattemplateLabelFor()gives, which is none where the field's plan names a group of controls througharia-labelledby.classNames: A string containing the base Bootstrap CSS classes, merged with any custom ones defined in your uiSchema.style: TheCSSPropertiesset by the field'sui:styleoption.label: The computed label for this field, as a string.keyName: The name of this field's property in its parent object, carrying none of the decorationlabelmay have picked up — aui:title, or the marker adeprecatedschema adds. The key of anadditionalPropertiesproperty is this rather than itslabel, so renaming one reads and writes the real key.description: A component instance rendering the field description, when the field's plan says the template draws it (this will use any customDescriptionFieldTemplatedefined in thetemplatespassed to theForm). Render it whenever it is present rather than deciding again fromdisplayLabel.rawDescription: The description the template draws, from the schema or aui:description, or empty where the plan leaves it to the field or its widget.children: The field or widget component instance for this field row.errors: A component instance listing any encountered errors for this field, when the field's plan says the template draws them.rawErrors: An array of strings listing the generated error messages this field is displaying,undefinedwhileui:hideErroris in effect. Deprecated, and kept through v7 for a template rendered without a plan: readpresentation.errors.messages, which hasui:hideErrorapplied, andpresentation.errors.byfor whether this template draws them, instead, orhasErrorsfor the field's error state.errorSchema: The tree of errors for this field and its children, carrying every error whateverhideErrorsays.help: A component instance rendering anyui:helpuiSchema directive defined, when the field's plan says the template draws it.rawHelp: Theui:helpuiSchema directive as it was given, astringor aReactElement, resolved the same way as thehelpcomponent that renders it, so it is a truthy check for whether the field has any help at all.hidden: A boolean value stating if the field should be hidden.required: A boolean value stating if the field is required. Mark the label you draw fromtemplateMarksRequired(), which follows the field's plan, so a checkbox the schema lets befalseisn't marked.readonly: A boolean value stating if the field is read-only.hideError: A boolean value stating if the field is hiding its errorshasErrors: Whether the field shows its own errors, asui:hideErrorleaves them, the state its label, description and help take. Beneath ananyOf/oneOffield it can differ frompresentation.errors, which are the field above's where it shows them.SchemaFieldsets it; a custom field that renders aFieldTemplateitself passes it with theerrors.disabled: A boolean value stating if the field is disabled.displayLabel: A boolean value stating if the template renders the label: true only where the field's plan says the template draws it, so it is false where the widget draws its own label, and whereui:label: falseturns it off. Deprecated, and kept through v7 for a template rendered without a plan: readpresentation.label.by === 'template'instead, ortemplateDrawsLabel(), which falls back todisplayLabelwithout a plan.presentation: The field's plan, built bySchemaField: who draws its label, description, help and errors, under which ids, and the attributes its control carries. SeeresolveFieldPresentation(). Where the template draws the label, render the label's text, without the required marker, in an element with the idpresentation.label.id, as core'sFieldLabeldoes with itslabelId. A<label for>names only the control it points at, so a control or a group whose plan gives itaria-labelledby, and the open list of options of@rjsf/daisyui's and@rjsf/shadcn'sSelectWidget, are named through that id, and without it they have no name.schema: The schema object for this field.uiSchema: The uiSchema object for this field.onChange: The value change event handler; Can be called with a new value to change the value for this field.formData: The formData for this field.registry: Theregistryobject.
Note: you can only define a single global field template for a form, but you can set individual field templates per property using
"ui:FieldTemplate".
GridTemplate
The GridTemplate is the template that renders a theme dependent Grid for either a row or column.
While it declares only a few properties, it takes any other prop too, in order to support passing any of the properties associated with a Grid implementation for any theme.
A prop it doesn't declare can't be read from it, so a template that reads one declares it on its own props, as in GridTemplateProps & { gap?: number }.
If you want to customize how grids are rendered you can.
import Grid from '@mui/material/Grid';
import type { GridTemplateProps, RJSFSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
import classNames from 'classnames';
const schema: RJSFSchema = {
type: 'string',
title: 'My input',
description: 'input description',
};
function GridTemplate(props: GridTemplateProps) {
const { children, column, className, fieldId, span, ...rest } = props;
return (
<Grid
container={!column}
size={column ? span : undefined}
{...rest}
className={classNames(className, 'my-custom-grid-styling')}
>
{children}
</Grid>
);
}
render(<Form schema={schema} validator={validator} templates={{ GridTemplate }} />, document.getElementById('app'));
The following props are passed to the GridTemplate:
children: The contents of the grid templatecolumn: Optional flag indicating whether the grid element represents a column, necessary for themes which have components for Rows vs Columnspan: Optional number of twelfths of a row a column spans, which every theme'sGridTemplateconverts to its own gridclassName: Optional class names to add to the grid elementstyle: Optional style to apply to the grid elementfieldId: For a column, the id of the first field it holds; for a row, or a column holding no field of its own, the id of the field whose layout grid holds it. It's for naming the row or column in a warning; keep it off the element you render
MarkdownTemplate
The MarkdownTemplate renders field descriptions, ui:help text and the translatable strings that allow markdown.
The core default renders them as plain text, so no markdown library is bundled.
@rjsf/core/markdown exports a MarkdownTemplate built on markdown-to-jsx with raw HTML parsing disabled; markdown-to-jsx is an optional peer dependency, so install it alongside @rjsf/core when you use this entry point.
Register it and enable markdown for descriptions or help independently:
import Form from '@rjsf/core';
import MarkdownTemplate from '@rjsf/core/markdown';
import { RJSFSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = { type: 'string', description: '**bolded** text in the description' };
render(
<Form
schema={schema}
validator={validator}
templates={{ MarkdownTemplate }}
uiSchema={{ 'ui:globalOptions': { enableMarkdownInDescription: true, enableMarkdownInHelp: true } }}
/>,
document.getElementById('app'),
);
Like any template it can also be registered in a theme, or swapped per field with the ui:MarkdownTemplate uiSchema directive.
Because the template is the renderer, any markdown behaviour is yours to choose: register your own component to use a different library, or to pass different options to markdown-to-jsx.
Raw HTML, which the @rjsf/core/markdown renderer disables, is the common case:
import { Markdown } from 'markdown-to-jsx/react';
import { MarkdownTemplateProps } from '@rjsf/utils';
/** Renders raw HTML embedded in markdown. Only register this when you control the markdown text — HTML from an
* untrusted source can inject scripts and styles into your page.
*/
function UnsafeHtmlMarkdownTemplate({ children }: MarkdownTemplateProps) {
return <Markdown>{children}</Markdown>;
}
The following props are passed to the MarkdownTemplate:
children: The markdown text to render.uiSchema: The uiSchema of the field whose text is being rendered, so a renderer can honour per-fieldui:options.registry: Theregistryobject.
MultiSchemaFieldTemplate
Each theme implements a MultiSchemaFieldTemplate used to render the layout of a MultiSchemaField, i.e. a field described by a oneOf or anyOf schema.
The template typically renders a Widget used to select the schema to use, as well as a field for the selected schema.
import { MultiSchemaFieldTemplateProps, RJSFSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'object',
properties: {
myField: {
oneOf: [
{
type: 'string',
title: 'String Field',
description: 'A field that accepts a string',
},
{
type: 'number',
title: 'Number Field',
description: 'A field that accepts a number',
},
],
},
},
};
function MultiSchemaFieldTemplate(props: MultiSchemaFieldTemplateProps) {
const { selector, optionSchemaField } = props;
return (
<div className='my-multi-schema-field-class'>
{selector}
<hr />
{optionSchemaField}
</div>
);
}
render(
<Form schema={schema} validator={validator} templates={{ MultiSchemaFieldTemplate }} />,
document.getElementById('app'),
);
The following props are passed to the MultiSchemaFieldTemplate:
id: The id of the field whose option is selected, which the selected option's field shares, and whose own errors theselectoris given. It is unset when the template rendersFallbackFieldTemplate's type selector, which isn't given them.selector: The rendered Widget used to select a multischema option.optionSchemaField: The rendered SchemaField representing the selected option.schema: The schema object for the field.uiSchema: The uiSchema object for the field.registry: Theregistryobject.
ObjectFieldTemplate
import { ObjectFieldTemplateProps, RJSFSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'object',
title: 'Object title',
description: 'Object description',
properties: {
name: {
type: 'string',
},
age: {
type: 'number',
},
},
};
function ObjectFieldTemplate(props: ObjectFieldTemplateProps) {
return (
<div>
{props.title}
{props.description}
{props.properties.map((element) => (
<div className='property-wrapper' key={element.content.key}>
{element.content}
</div>
))}
</div>
);
}
render(
<Form schema={schema} validator={validator} templates={{ ObjectFieldTemplate }} />,
document.getElementById('app'),
);
You also can provide your own field template to a uiSchema by specifying a ui:ObjectFieldTemplate property with your Component :
import { UiSchema } from '@rjsf/utils';
import ObjectFieldTemplate from './ObjectFieldTemplate';
const uiSchema: UiSchema = {
'ui:ObjectFieldTemplate': ObjectFieldTemplate,
};
or a string value from the Registry :
import { UiSchema } from '@rjsf/utils';
const uiSchema: UiSchema = {
'ui:ObjectFieldTemplate': 'ObjectFieldTemplate',
};
Please see the customObject.tsx sample from the playground for a better example.
The following props are passed to each ObjectFieldTemplate as defined by the ObjectFieldTemplateProps in @rjsf/utils:
title: A string value containing the title for the object.optionalDataControl: The control that adds or removes the data of an optional object, when it has one.titleDrawsOptionalDataControl()says whether to lay it out in the heading drawn fortitleor with the properties, so it isn't dropped with a heading that isn't drawn.presentation: The object's plan: whether its heading and description are this template's to draw, which they aren't when they repeat the field above it, and the id its description renders under. It also carries the object's own errors,presentation.errors.messages, withui:hideErrorapplied, which this template draws, underpresentation.errors.id, only wherepresentation.errors.byis'self'; under'template'theFieldTemplatedraws them.getErrorsToDraw()gives the messages this template draws. SeeresolveFieldPresentation().description: A string value containing the description for the object.disabled: A boolean value stating if the object is disabled.properties: An array of object representing the properties in the object. Each of the properties represent a child with properties described below.onAddProperty: () => void: Callback to use in order to add an new additionalProperty to the object field (to be used with additionalProperties and patternProperties)addButtonProps: Props to spread onto the object'sAddButton,{ title }, which title it after the object's title or name, such asAdd Address; undefined when the object has neither, or whentranslateStringgives an emptyTranslatableString.AddNamedButton.readonly: A boolean value stating if the object is read-only.required: A boolean value stating if the object's heading carries the required marker: where the object is required, unless a field above rendering the same id draws the marked label, as ananyOf/oneOffield does for its option.hideError: A boolean value stating if the field is hiding its errors.schema: The schema object for this object.uiSchema: The uiSchema object for this object field.id: The id of the field in the hierarchy.errorSchema: The optional validation errors in the form of anErrorSchemahasErrors: Whether the object shows its own errors, asui:hideErrorleaves them. Beneath ananyOf/oneOffield it can differ frompresentation.errors.messages, which are the field above's where that field shows them. An object rendered besideanyOf/oneOfoptions of its own leaves its errors to the selected option, so it isfalsethere.rawErrors: An array of strings listing the object's own errors, whicherrorSchemadoesn't hold. Unlike therawErrorsaFieldTemplatereceives, it carries them whateverhideErrorsays. Deprecated, and kept through v7 for a template rendered without a plan: readgetErrorsToDraw()for the messages this template draws itself,presentation.errors.messages, withui:hideErrorapplied, wherepresentation.errors.byis'self', since theFieldTemplatedraws them under'template', andhasErrorsfor an error state, instead.getErrorsToDraw()falls back torawErrorswithhideErrorwithout a plan.formData: The form data for the object.registry: Theregistryobject.
The following props are part of each element in properties:
content: The html for the property's content. Key anything you wrap it in bycontent.keyrather thanname, which anadditionalPropertieskey's rename changes, remounting the field and losing what its widget holds.name: A string representing the property name.disabled: A boolean value stating if the object property is disabled.readonly: A boolean value stating if the property is read-only.hidden: A boolean value stating if the property should be hidden: whether its field renders hidden throughui:widget: 'hidden'or adeprecatedHandlingof'hide', as itsFieldTemplateis told. It can change with the data, such as for a property thatdependenciesorif/thenmarkdeprecated, and a template that renders a hidden property under another parent, or leaves it out, mounts the property's field afresh when it does. It is decided the way the defaultSchemaFieldandCyclicSchemaFieldresolve the property, see Custom SchemaField.renderedAs: A function returning what the property's field renders as:field, the registry key aui:fieldor the schema's$idnames, if any;widget, the widget it renders, when that is named by a string; andtype, the type in itsrjsf-field-<type>class name. A field whoseanyOf/oneOfoption renders its control reports the widget of the option its data matches, and that option'sfieldandtypewhere it names none of its own, as an untypedanyOfdoes. Only that outer option is read, so an option that is itself an untypedanyOf/oneOfreports nothing of the option it shows. It resolves the property's schema again, so call it only when you need it. Likehidden, it is decided the way the defaultSchemaFieldandCyclicSchemaFieldresolve the property. A custom field that buildspropertiesitself may leave it out, or set it withcreateSchemaFieldRenderedAs()from@rjsf/core, calling the function that returns with what it hands the property'sSchemaField:schema,uiSchema,formData,fieldPathandregistry. That function keeps its last result, so one kept per property across renders reuses it while the property is unchanged, where one created inrenderedAsresolves the property on every call.@rjsf/antdkeys a property with norenderedAsby nothing, so it gets the default column span.
Note: Array and object field templates are always rendered inside the FieldTemplate. To fully customize an object field template, you may need to specify both
ui:FieldTemplateandui:ObjectFieldTemplate.
OptionalDataControlsTemplate
Each theme implements a OptionalDataControlsTemplate used to render the Optional Data Controls when that feature has been enabled
import { OptionalDataControlsTemplateProps, RJSFSchema } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
title: 'test',
properties: {
nestedObjectOptional: {
type: 'object',
properties: {
test: {
type: 'string',
},
},
},
nestedArrayOptional: {
type: 'array',
items: {
type: 'string',
},
},
},
};
const uiSchema = {
'ui:globalOptions': {
enableOptionalDataFieldForType: ['object', 'array'],
},
};
const defaultFormStateBehavior = {
// Set the emptyObjectFields to only populate required defaults to highlight the code working
emptyObjectFields: 'populateRequiredDefaults',
};
function OptionalDataControlsTemplate(props: OptionalDataControlsTemplateProps) {
const { id, registry, label, onAddClick, onRemoveClick } = props;
if (onAddClick) {
return (
<button id={id} className='rjsf-add-optional-data' onClick={onAddClick} title={label}>
+
</button>
);
} else if (onRemoveClick) {
return (
<button id={id} className='rjsf-remove-optional-data' onClick={onRemoveClick} title={label}>
-
</button>
);
}
return <em id={id}>{label}</em>;
}
render(
<Form
schema={schema}
validator={validator}
uiSchema={uiSchema}
defaultFormStateBehavior={defaultFormStateBehavior}
templates={{ OptionalDataControlsTemplate }}
/>,
document.getElementById('app'),
);
The following props are passed to each OptionalDataControlsTemplate as defined by the OptionalDataControlsTemplateProps in @rjsf/utils:
id: The generated id for this Optional Data Control instance.label: The label to use for the Optional Data ControlonAddClick: Optional callback to call when clicking on the Optional Data Control to add dataonRemoveClick: Optional callback to call when clicking on the Optional Data Control to remove dataschema: The schema object for this object.uiSchema: The uiSchema object for this object field.registry: Theregistryobject.
TitleFieldTemplate
Each theme implements a TitleFieldTemplate used to render the title of a field.
If you want to customize how titles are rendered you can.
import { RJSFSchema, TitleFieldProps } from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'string',
title: 'My input',
description: 'input description',
};
function TitleFieldTemplate(props: TitleFieldProps) {
const { id, required, title } = props;
return (
<header>
<span id={id}>{title}</span>
{required && <mark>*</mark>}
</header>
);
}
render(
<Form schema={schema} validator={validator} templates={{ TitleFieldTemplate }} />,
document.getElementById('app'),
);
The following props are passed to each TitleFieldTemplate:
id: The id of the title, which an object'sanyOf/oneOfoption selector is named by througharia-labelledby. Put it on the element holding the title's text alone, so the selector's name leaves out the required marker and the optional data control.title: The title of the field being rendered.schema: The schema object for the field.uiSchema: The uiSchema object for the field.required: A boolean value stating if the field is requiredregistry: Theregistryobject.outsideFieldset: Set where the title heads no<fieldset>, such as a layout grid's header, so a template that renders a<legend>renders an element valid there instead, as@rjsf/core's renders a<div class="rjsf-title">.
UnsupportedFieldTemplate
The UnsupportedField component is used to render a field in the schema is one that is not supported by react-jsonschema-form.
If you want to customize how an unsupported field is rendered (perhaps for localization purposes) you can.
import { RJSFSchema, UnsupportedFieldProps } from '@rjsf/utils';
import { FormattedMessage } from 'react-intl';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'invalid',
};
function UnsupportedFieldTemplate(props: UnsupportedFieldProps) {
const { schema, reason } = props;
return (
<div>
<FormattedMessage defaultMessage='Unsupported field schema, reason = {reason}' value={{ reason }} />
<pre>{JSON.stringify(schema, null, 2)}</pre>
</div>
);
}
render(
<Form schema={schema} validator={validator} templates={{ UnsupportedFieldTemplate }} />,
document.getElementById('app'),
);
The following props are passed to each UnsupportedFieldTemplate:
schema: The schema object for this unsupported field.id: The id of the field in the hierarchy.reason: The reason why the schema field has an unsupported type.registry: Theregistryobject.
WrapIfAdditionalTemplate
The WrapIfAdditionalTemplate is used by the FieldTemplate to conditionally render additional controls if additionalProperties or patternProperties are present in the schema.
You may customize WrapIfAdditionalTemplate if you wish to change the layout or behavior of user-controlled additionalProperties and patternProperties.
Core's lays the key, the value and the remove button out on shared grid rows, so the key's input sits level with the value's; see Lining up a custom FieldTemplate.
import {
ADDITIONAL_PROPERTY_FLAG,
additionalKeyId,
hasSchemaMarker,
isAdditionalKeyDisabled,
isAdditionalRemoveDisabled,
RJSFSchema,
WrapIfAdditionalTemplateProps,
} from '@rjsf/utils';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'object',
additionalProperties: true,
};
function WrapIfAdditionalTemplate(props: WrapIfAdditionalTemplateProps) {
const {
id,
keyName,
onKeyRenameBlur,
onRemoveProperty,
schema,
children,
uiSchema,
registry,
classNames,
style,
} = props;
const { RemoveButton } = registry.templates.ButtonTemplates;
const additional = hasSchemaMarker(schema, ADDITIONAL_PROPERTY_FLAG);
if (!additional) {
return <div>{children}</div>;
}
return (
<div className={classNames} style={style}>
<label htmlFor={additionalKeyId(id)}>Custom Field Key</label>
<input
className='form-control'
type='text'
id={additionalKeyId(id)}
disabled={isAdditionalKeyDisabled(props)}
onBlur={onKeyRenameBlur}
defaultValue={keyName}
/>
<div>{children}</div>
<RemoveButton
disabled={isAdditionalRemoveDisabled(props)}
onClick={onRemoveProperty}
uiSchema={uiSchema}
registry={registry}
/>
</div>
);
}
render(
<Form schema={schema} validator={validator} templates={{ WrapIfAdditionalTemplate }} />,
document.getElementById('app'),
);
The following props are passed to the WrapIfAdditionalTemplate:
-
children: The children of the component, typically specified by theFieldTemplate. -
id: The id of the field in the hierarchy. You can use it to render a label targeting the wrapped widget. -
classNames: A string containing the base Bootstrap CSS classes, merged with any custom ones defined in your uiSchema. -
style: TheCSSPropertiesset by the field'sui:styleoption. -
label: The computed label for this field, as a string. -
presentation: The field's plan. Whether to label the key input ishasAdditionalKeyLabel(): wherever the value's label is drawn, by the template or the value's own component. -
hasErrors: Whether the field shows its own errors, asui:hideErrorleaves them, which theFieldTemplatehands on from its ownhasErrors. Core'sWrapIfAdditionalTemplatetakes its error class from it alone, so aFieldTemplatethat lists the props it forwards one by one includes it. -
keyName: The name of this field's property in its parent object, carrying none of the decorationlabelmay have picked up — aui:title, or the marker adeprecatedschema adds. The key of anadditionalPropertiesproperty is this rather than itslabel, so renaming one reads and writes the real key. -
required: A boolean value stating if the field is required. -
readonly: A boolean value stating if the field is read-only. -
disabled: A boolean value stating if the field is disabled. -
schema: The schema object for this field. -
uiSchema: The uiSchema object for this field. -
onKeyRename: Optional callback used to handle the changing of an additional property key's name with the new value. It isundefinedfor a fieldObjectFielddoesn't render, such as the root or an array item, asonKeyRenameBlurandonRemovePropertyare, so check for it before calling it -
onKeyRenameBlur: Optional callback used to handle the changing of an additional property key's name when the input is blurred. The event's target's value will be used as the new value. Its a wrapper callback aroundonKeyRename. Disable the key input of a disabled or read-only field and of one handed noonKeyRenameBlur, whichisAdditionalKeyDisabled()works out -
onRemoveProperty: Optional callback used to handle the removal of the additionalProperty. Disable the remove button of a disabled or read-only field and of one handed noonRemoveProperty, whichisAdditionalRemoveDisabled()works out -
propertyNamesEnum: The key names this property may be renamed to, derived from the parent schema'spropertyNames.enumand narrowed to the names its siblings have not already taken;undefinedwhen the parent schema does not enumerate its property names. Render the key as a dropdown of those names when it is provided, which theAdditionalPropertyKeySelectcomponent from@rjsf/utilsdoes using the theme's ownSelectWidget -
keyNotAllowed: Whether the parent schema forbids this property's key, which its row's errors then say. Mark the key input invalid while it is, whichgetAdditionalKeyAttributes()from@rjsf/utilsdoes
ButtonTemplates
There are several buttons that are potentially rendered in the Form.
Each of these buttons have been customized in the themes, and can be customized by you as well.
All but one of these buttons (i.e. the SubmitButton) are rendered currently as icons with title text for a description.
Each button template (except for the SubmitButton) accepts, as props, the standard HTML button attributes along with the following:
iconType: An alternative specification for the type of the icon button.icon: The name representation or actual react element implementation for the icon.@rjsf/core'sIconButtondraws onlyplus,copy,arrow-up,arrow-downandremove, and no icon for any other name.uiSchema: The uiSchema object for this field.registry: Theregistryobject.
AddButton
The AddButton is used to render an add action on a Form for both a new additionalProperties or patternProperties element for an object or a new element in an array.
An expandable object's AddButton is passed a title naming the object, such as Add Address; an array's is passed none.
You can customize the AddButton to render something other than the icon button that is provided by a theme as follows:
import React from 'react';
import { IconButtonProps, RJSFSchema } from '@rjsf/utils';
import { FormattedMessage } from 'react-intl';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'array',
items: { type: 'string' },
};
function AddButton(props: IconButtonProps) {
const { icon, iconType, registry, uiSchema, ...btnProps } = props;
return (
<button type='button' {...btnProps}>
{icon} <FormattedMessage defaultMessage='Add' />
</button>
);
}
render(
<Form schema={schema} validator={validator} templates={{ ButtonTemplates: { AddButton } }} />,
document.getElementById('app'),
);
ClearButton
The ClearButton is rendered by BaseInputTemplate to clear a text input's value when the allowClearTextInputs option is enabled.
You can customize the ClearButton to render something other than the icon button that is provided by a theme as follows:
import React from 'react';
import { IconButtonProps, RJSFSchema, UiSchema } from '@rjsf/utils';
import { FormattedMessage } from 'react-intl';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'string',
};
const uiSchema: UiSchema = {
'ui:options': { allowClearTextInputs: true },
};
function ClearButton(props: IconButtonProps) {
const { icon, iconType, registry, uiSchema, ...btnProps } = props;
return (
<button type='button' {...btnProps}>
{icon} <FormattedMessage defaultMessage='Clear' />
</button>
);
}
render(
<Form
schema={schema}
uiSchema={uiSchema}
formData='Clear me'
validator={validator}
templates={{ ButtonTemplates: { ClearButton } }}
/>,
document.getElementById('app'),
);
CopyButton
The CopyButton is rendered by ArrayFieldItemButtonsTemplate to duplicate an array item when the copyable option is enabled (it is off by default).
You can customize the CopyButton to render something other than the icon button that is provided by a theme as follows:
import React from 'react';
import { IconButtonProps, RJSFSchema, UiSchema } from '@rjsf/utils';
import { FormattedMessage } from 'react-intl';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'array',
items: { type: 'string' },
};
const uiSchema: UiSchema = {
'ui:options': { copyable: true },
};
function CopyButton(props: IconButtonProps) {
const { icon, iconType, registry, uiSchema, ...btnProps } = props;
return (
<button type='button' {...btnProps}>
{icon} <FormattedMessage defaultMessage='Copy' />
</button>
);
}
render(
<Form
schema={schema}
uiSchema={uiSchema}
formData={['first', 'second']}
validator={validator}
templates={{ ButtonTemplates: { CopyButton } }}
/>,
document.getElementById('app'),
);
MoveDownButton
The MoveDownButton is used to render a move down action on a Form for elements in an array.
You can customize the MoveDownButton to render something other than the icon button that is provided by a theme as follows:
import React from 'react';
import { IconButtonProps, RJSFSchema } from '@rjsf/utils';
import { FormattedMessage } from 'react-intl';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'array',
items: { type: 'string' },
};
function MoveDownButton(props: IconButtonProps) {
const { icon, iconType, registry, uiSchema, ...btnProps } = props;
return (
<button type='button' {...btnProps}>
{icon} <FormattedMessage defaultMessage='Move Down' />
</button>
);
}
render(
<Form
schema={schema}
formData={['first', 'second']}
validator={validator}
templates={{ ButtonTemplates: { MoveDownButton } }}
/>,
document.getElementById('app'),
);
MoveUpButton
The MoveUpButton is used to render a move up action on a Form for elements in an array.
You can customize the MoveUpButton to render something other than the icon button that is provided by a theme as follows:
import React from 'react';
import { IconButtonProps, RJSFSchema } from '@rjsf/utils';
import { FormattedMessage } from 'react-intl';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'array',
items: { type: 'string' },
};
function MoveUpButton(props: IconButtonProps) {
const { icon, iconType, registry, uiSchema, ...btnProps } = props;
return (
<button type='button' {...btnProps}>
{icon} <FormattedMessage defaultMessage='Move Up' />
</button>
);
}
render(
<Form
schema={schema}
formData={['first', 'second']}
validator={validator}
templates={{ ButtonTemplates: { MoveUpButton } }}
/>,
document.getElementById('app'),
);
RemoveButton
The RemoveButton is used to render a remove action on a Form for both a existing additionalProperties or patternProperties element for an object or an existing element in an array.
You can customize the RemoveButton to render something other than the icon button that is provided by a theme as follows:
import React from 'react';
import { IconButtonProps, RJSFSchema } from '@rjsf/utils';
import { FormattedMessage } from 'react-intl';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'array',
items: { type: 'string' },
};
function RemoveButton(props: IconButtonProps) {
const { icon, iconType, registry, uiSchema, ...btnProps } = props;
return (
<button type='button' {...btnProps}>
{icon} <FormattedMessage defaultMessage='Remove' />
</button>
);
}
render(
<Form
schema={schema}
formData={['first', 'second']}
validator={validator}
templates={{ ButtonTemplates: { RemoveButton } }}
/>,
document.getElementById('app'),
);
SubmitButton
The SubmitButton is already very customizable via the UISchemaSubmitButtonOptions capabilities in the uiSchema but it can also be fully customized as you see fit.
NOTE: However you choose to implement this, making it something other than a
submittypebuttonmay result in theFormnot submitting when pressed. You could also choose to provide your own submit button as the children prop of theFormshould you so choose.
import React from 'react';
import { getSubmitButtonOptions, RJSFSchema, SubmitButtonProps } from '@rjsf/utils';
import { FormattedMessage } from 'react-intl';
import validator from '@rjsf/validator-ajv8';
const schema: RJSFSchema = {
type: 'string',
};
function SubmitButton(props: SubmitButtonProps) {
const { uiSchema } = props;
const { norender } = getSubmitButtonOptions(uiSchema);
if (norender) {
return null;
}
return (
<button type='submit'>
<FormattedMessage defaultMessage='Okay' />
</button>
);
}
render(
<Form schema={schema} validator={validator} templates={{ ButtonTemplates: { SubmitButton } }} />,
document.getElementById('app'),
);
The following props are passed to a SubmitButton:
uiSchema: The uiSchema object for this field, used to extract theUISchemaSubmitButtonOptions.registry: Theregistryobject.pending: Whether a submission is in flight: a promiseonSubmitreturned has yet to settle, or the form is pending in React's form status, as it is while a transitiononSubmitstarted runs. Meanwhile the form setsaria-disabledand anonClickthat cancels the click in the props of theUISchemaSubmitButtonOptions, so a button that spreads those props takes no second submit and stays focusable. Don't setdisabledfrompending, since the browser moves focus off a focused button that becomes disabled. Usependingto show the submission, such as with a spinner or a style foraria-disabled. See Submitting.
Registering Templates
You can now add custom components to the registry and reference them in your uiSchema using string keys.
Adding Custom Templates to the Registry
import CustomArrayFieldTemplate from './CustomArrayFieldTemplate';
import { UiSchema } from '@rjsf/utils';
// Add the custom template to the registry
const registry = { templates: { CustomArrayFieldTemplate } };
// Use the custom template in the uiSchema
const uiSchema: UiSchema = { 'ui:ArrayFieldTemplate': 'CustomArrayFieldTemplate' };
Reading a custom template back
RJSF doesn't know the props of a template you register under your own name, so one read back from registry.templates or getTemplates() under that name has props of type never and can't be rendered as it is. Name its props with isComponentType(), which also checks that it is a component:
import { isComponentType, Registry } from '@rjsf/utils';
import { MyTemplateProps } from './MyTemplate';
function renderMyTemplate(registry: Registry, props: MyTemplateProps) {
const { MyTemplate } = registry.templates;
if (!isComponentType<MyTemplateProps>(MyTemplate)) {
return null;
}
return <MyTemplate {...props} />;
}
For a template in a group of your own, narrow the group first, since isComponentType() is false for it, then name the props on the member. A typeof check alone isn't enough to find the group, because what memo(), forwardRef() and lazy() return is an object too:
const { MyGroup } = registry.templates;
if (typeof MyGroup !== 'object' || isComponentType(MyGroup)) {
return null;
}
const { MyTemplate } = MyGroup;
if (!isComponentType<MyTemplateProps>(MyTemplate)) {
return null;
}
return <MyTemplate {...props} />;
A custom template written inline with no type on its props parameter takes never from the same entry, so give it one: templates={{ MyTemplate: (props: MyTemplateProps) => <div>{props.title}</div> }}.
Typing a set of templates
PartialTemplatesType types a set of templates, as the templates prop of Form and a theme's templates take: it checks each template RJSF declares, such as FieldTemplate, against its own props, takes any of the ButtonTemplates on their own, and takes your own templates and groups of them beside those:
import { PartialTemplatesType } from '@rjsf/utils';
import MyFieldTemplate from './MyFieldTemplate';
import MySubmitButton from './MySubmitButton';
import MyTemplate from './MyTemplate';
const templates: PartialTemplatesType = {
FieldTemplate: MyFieldTemplate,
ButtonTemplates: { SubmitButton: MySubmitButton },
MyTemplate,
};
Partial<TemplatesType>, as every theme's generateTemplates() returns, checks the declared templates too, but Partial reaches only the top level, so a ButtonTemplates entry in it has to hold every button.
TemplatesType is two exported types put together: DeclaredTemplatesType holds the templates RJSF declares, and CustomTemplateEntries is the string index signature for your own. Omit with literal keys on TemplatesType or PartialTemplatesType, which has the same signature, such as Omit<TemplatesType, 'ButtonTemplates'>, collapses to that signature and checks none of the declared templates, so omit from DeclaredTemplatesType instead, and add CustomTemplateEntries when the type holds your own templates too. That signature takes a key you omitted unchecked, so declare it again with the type you want, such as a set that has to hold a FieldTemplate:
import { CustomTemplateEntries, DeclaredTemplatesType } from '@rjsf/utils';
type MyTemplates = Partial<Omit<DeclaredTemplatesType, 'FieldTemplate'>> & {
FieldTemplate: DeclaredTemplatesType['FieldTemplate'];
} & CustomTemplateEntries;
Pick keeps the templates it picks checked.