Skip to content
nahushrPublic

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

PolyForm

Build, analyze, and publish React 18+ TypeScript MIT license

Open the PolyForm example in StackBlitz

Demo

Online Local
Open the React example in StackBlitz npm ci → npm run dev:example → localhost:7001
Example Fixture Features
Complete form examples/vite-demo/src/App.tsx Every built-in field type, grouped into separate cards from one field array
Submit and inspect examples/vite-demo/src/App.tsx Submit displays the current React Hook Form values as formatted JSON; submit again to see edits

Install and import

npm install @simplishelf/polyform react react-dom react-hook-form @mui/material @mui/icons-material @mui/x-date-pickers @emotion/react @emotion/styled react-toastify

PolyForm also installs its field-specific dependencies for rich text and phone input. If you use the Address field with the built-in country/state/city lookup, install the optional dataset package:

npm install country-state-city

Import the package stylesheet once in your app entry:

import "@simplishelf/polyform/style.css";

Mount a ToastContainer from react-toastify in your app if you use the included file or image upload controls; those controls use it to show upload validation and status messages.

One configuration for multiple cards

Put the form fields in one array and arrange slices of that array into as many cards and sections as needed. Each card can have its own header, subtitle, and styling. A notes card is another item in the same cards structure.

import { useForm } from "react-hook-form";
import { FieldType, PolyForm, type FormCardConfig } from "@simplishelf/polyform";

interface LeadFormData {
  firstName: string;
  email: string;
  notes: string;
}

const fields = [
  { name: "firstName", label: "First name", required: true },
  { name: "email", label: "Email", type: FieldType.Email, required: true },
  { name: "notes", label: "Notes", type: FieldType.Textarea, rows: 4 },
] satisfies import("@simplishelf/polyform").FieldConfig<LeadFormData>[];

const cards: FormCardConfig<LeadFormData>[] = [
  {
    header: "Lead information",
    subtitle: "Contact details",
    sections: [{ fields: fields.slice(0, 2) }],
  },
  {
    header: "Notes",
    subtitle: "Add useful context for the team",
    sections: [{ fields: fields.slice(2) }],
  },
];

function LeadForm() {
  const { control, handleSubmit, setValue, trigger, formState: { errors } } =
    useForm<LeadFormData>();

  return (
    <form onSubmit={handleSubmit((values) => console.log(values))}>
      <PolyForm
        cards={cards}
        control={control}
        errors={errors}
        setValue={setValue}
        trigger={trigger}
        classNames={{
          card: "lead-card",
          cardTitle: "lead-card__title",
          cardSubtitle: "lead-card__subtitle",
        }}
      />
      <button type="submit">Submit</button>
    </form>
  );
}

classNames accepts class names for the root, card, card header/title/subtitle/divider, sections, and field grid items. Each card and section can also override its own classes with className, headerClassName, titleClassName, subtitleClassName, and related section props. A horizontal divider appears below each card heading. Set titleTypography and subtitleTypography per card to customize fontStyle, color, fontSize, and fontFamily. View mode has its own summary layout and accepts viewRoot, viewCard, viewCardTitle, viewSection, and related view* class names for independent styling.

Optional test-data button

Import PolyFormTestFillButton alongside PolyForm and render it inside the same native <form>. It fills all registered PolyForm fields with realistic sample values. Choice fields use configured options, and LazyAutocomplete calls its fetchOptions function and only selects a returned option. If a custom field manages its value outside React Hook Form, give that field a testValue factory.

import { useForm } from "react-hook-form";
import { PolyForm, PolyFormTestFillButton } from "@simplishelf/polyform";

function LeadForm() {
  const { control, handleSubmit, setValue, trigger, formState: { errors } } =
    useForm<LeadFormData>();

  return (
    <form onSubmit={handleSubmit((values) => console.log(values))}>
      <PolyForm
        cards={cards}
        control={control}
        errors={errors}
        setValue={setValue}
        trigger={trigger}
      />
      <PolyFormTestFillButton className="lead-form__test-fill" />
      <button type="submit">Submit</button>
    </form>
  );
}

PolyFormTestFillButton accepts only a className for styling. Forms with address fields should pass setValue to PolyForm, as they do for normal controlled updates.

Read-only view mode

Set isView to render a separate, responsive data summary. It does not render the edit form's inputs, custom edit slots, or actions. Pass values to render directly from a data object; in that data-only mode, control and errors are optional. If you omit values, PolyForm reads the field values from React Hook Form's control.

<PolyForm<LeadFormData> cards={cards} values={lead} isView />
const { control, watch, formState: { errors } } = useForm<LeadFormData>();
const values = watch();

<PolyForm
  cards={cards}
  control={control}
  errors={errors}
  values={values}
  isView={isViewMode}
/>

The read-only presenter formats phone numbers with country flags, currency values with their currency symbol and flag, and addresses, date ranges, choices, ratings, colors, images, files, code, and key-value metadata with layouts tailored to each type. Passwords are masked. Numeric fields can name a related currency field to display currency formatting:

{
  name: "priceRange",
  label: "Price range",
  type: FieldType.RangeSlider,
  currencyFieldName: "currency",
}

For custom fields, viewContent(value, values) can return the display content used in view mode. The example page includes an edit/view toggle and uses watch() so edits appear in the summary immediately.

Supported field types

Text, Email, Phone, Password, Number, Date, DateRange, DateTime, Time, Select, Autocomplete, LazyAutocomplete, Textarea, RichText, Image, MultipleImage, MultipleFile, Code, Checkbox, MultiCheckbox, Radio, RadioGroup, MultiSelect, LeadLabels, Address, Switch, Currency, Slider, RangeSlider, Rating, EmojiText, Color, KeyValue, and KeyValueSelect.

Field types Value / configuration
Text, Email, Phone, Password, Textarea, Code String values. Code supports TypeScript, JavaScript, Python, SQL, JSON, HTML, CSS, and plain text.
Number, Slider, Rating Number values; Rating also accepts null. Configure sliders with sliderMin, sliderMax, sliderStep, sliderMarks, and sliderUnit.
Date, DateTime, Time Date values or null; DateTimeValue keeps the selected date and timezone together.
DateRange One field stores a DateRangeValue object with start and end dates and uses a connected range picker.
Select, Autocomplete, LazyAutocomplete, Currency Single values. Lazy options use fetchOptions; currency selection includes searchable currency choices.
MultiSelect, LeadLabels Chip-based multi-values. LeadLabels accepts LeadLabelOption[] and leadLabelOptions, with colored chips and label creation.
Checkbox, Switch, Radio Boolean values.
MultiCheckbox, RadioGroup String or number choices from options; set row: true for a horizontal layout.
Image One image value.
MultipleImage Record<string, string> of image previews; select a batch together, inspect every preview, and remove individual images.
MultipleFile File[] with selected file names, sizes, and per-file removal. Upload fields accept maxFiles, maxSizeMB, and accept.
Address Address object. Supports built-in country, state, and city lookup when country-state-city is installed.
RichText HTML content from the rich-text editor.
EmojiText Searchable emoji picker with the full emoji list and cursor-aware insertion; maxLength sets the character limit.
Color CSS color string such as hex or RGB, with a preview swatch.
KeyValue, KeyValueSelect KeyValueEntry[] metadata rows; the select variant supports shared or per-key keyOptions, valueOptions, and valueOptionsByKey.

See examples/vite-demo for a runnable form that renders every built-in field from one configuration array across separate cards. Its submit handler belongs to the application: the example uses React Hook Form's handleSubmit to show the values as JSON, and updates that JSON each time the form is submitted.

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages