Skip to the content

Lesson 175 of 296

Config-driven UI from JSON

What you will learn

  • What config-driven (schema-driven) UI is
  • Rendering a form from a JSON schema
  • Validation driven by the same config
  • Component registries
  • When this pattern is worth it
On this page

What is config-driven UI?

Instead of writing a component by hand for every form or dashboard, describe it in data (JSON), and write one renderer that turns the data into UI. Examples:

  • A CMS or admin panel where non-developers build forms.
  • A survey or onboarding tool with many different questionnaires.
  • Dashboards where users choose and arrange widgets.
  • Different forms per client or per country, loaded from an API.

A task from your study plan: build a form that renders from a JSON schema with validation.

The schema

TSX
type FieldConfig =
  | { kind: "text"; name: string; label: string; required?: boolean; maxLength?: number }
  | { kind: "email"; name: string; label: string; required?: boolean }
  | { kind: "number"; name: string; label: string; required?: boolean; min?: number; max?: number }
  | { kind: "select"; name: string; label: string; required?: boolean; options: { value: string; label: string }[] }
  | { kind: "checkbox"; name: string; label: string; required?: boolean };

type FormConfig = { id: string; title: string; submitLabel: string; fields: FieldConfig[] };

type FormValues = Record<string, string | boolean>;

const contactFormConfig: FormConfig = {
  id: "contact",
  title: "Contact us",
  submitLabel: "Send",
  fields: [
    { kind: "text", name: "name", label: "Full name", required: true, maxLength: 80 },
    { kind: "email", name: "email", label: "Email", required: true },
    { kind: "number", name: "age", label: "Age", min: 16, max: 120 },
    {
      kind: "select",
      name: "topic",
      label: "Topic",
      required: true,
      options: [
        { value: "sales", label: "Sales" },
        { value: "support", label: "Support" }
      ]
    },
    { kind: "checkbox", name: "consent", label: "I agree to be contacted", required: true }
  ]
};

The field types form a discriminated union (Lesson 107), so each kind has exactly the options it needs, and the renderer can switch on kind safely.

Validation from the same config

A pure function: easy to test and reusable on the server.

TSX
function validateField(field: FieldConfig, value: string | boolean | undefined): string | null {
  if (field.kind === "checkbox") {
    return field.required && value !== true ? `${field.label} is required` : null;
  }
  const text = typeof value === "string" ? value.trim() : "";
  if (text === "") return field.required ? `${field.label} is required` : null;

  switch (field.kind) {
    case "text":
      return field.maxLength !== undefined && text.length > field.maxLength
        ? `${field.label} must be ${field.maxLength} characters or fewer`
        : null;
    case "email":
      return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(text) ? null : "Enter a valid email address";
    case "number": {
      const n = Number(text);
      if (!Number.isFinite(n)) return `${field.label} must be a number`;
      if (field.min !== undefined && n < field.min) return `${field.label} must be at least ${field.min}`;
      if (field.max !== undefined && n > field.max) return `${field.label} must be at most ${field.max}`;
      return null;
    }
    case "select":
      return field.options.some((o) => o.value === text) ? null : `Choose a valid ${field.label.toLowerCase()}`;
  }
}

function validateForm(config: FormConfig, values: FormValues): Record<string, string> {
  const errors: Record<string, string> = {};
  for (const field of config.fields) {
    const error = validateField(field, values[field.name]);
    if (error) errors[field.name] = error;
  }
  return errors;
}

The renderer

TSX
function FieldInput({
  field,
  value,
  error,
  onChange
}: {
  field: FieldConfig;
  value: string | boolean | undefined;
  error?: string;
  onChange: (value: string | boolean) => void;
}) {
  const id = `field-${field.name}`;
  const errorId = `${id}-error`;
  const common = {
    id,
    name: field.name,
    "aria-invalid": error ? true : undefined,
    "aria-describedby": error ? errorId : undefined
  };

  let control: ReactNode;
  switch (field.kind) {
    case "checkbox":
      control = (
        <input {...common} type="checkbox" checked={value === true} onChange={(e) => onChange(e.target.checked)} />
      );
      break;
    case "select":
      control = (
        <select {...common} value={typeof value === "string" ? value : ""} onChange={(e) => onChange(e.target.value)}>
          <option value="">Please choose</option>
          {field.options.map((o) => (
            <option key={o.value} value={o.value}>{o.label}</option>
          ))}
        </select>
      );
      break;
    default:
      control = (
        <input
          {...common}
          type={field.kind}
          value={typeof value === "string" ? value : ""}
          onChange={(e) => onChange(e.target.value)}
        />
      );
  }

  return (
    <div className="field">
      <label htmlFor={id}>
        {field.label}
        {field.required ? " (required)" : ""}
      </label>
      {control}
      {error && <p id={errorId} role="alert">{error}</p>}
    </div>
  );
}

function SchemaForm({ config, onSubmit }: { config: FormConfig; onSubmit: (values: FormValues) => void }) {
  const [values, setValues] = useState<FormValues>({});
  const [errors, setErrors] = useState<Record<string, string>>({});

  function handleSubmit(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const found = validateForm(config, values);
    setErrors(found);
    if (Object.keys(found).length === 0) onSubmit(values);
  }

  return (
    <form onSubmit={handleSubmit} noValidate aria-labelledby={`${config.id}-title`}>
      <h2 id={`${config.id}-title`}>{config.title}</h2>
      {config.fields.map((field) => (
        <FieldInput
          key={field.name}
          field={field}
          value={values[field.name]}
          error={errors[field.name]}
          onChange={(v) => setValues((prev) => ({ ...prev, [field.name]: v }))}
        />
      ))}
      <button type="submit">{config.submitLabel}</button>
    </form>
  );
}

Points worth explaining:

  • Field names are used as keys (they must be unique in the config).
  • Accessibility is built in once for every generated form: labels, required markers in text, aria-invalid, and errors linked with aria-describedby (Lesson 13).
  • Validation runs on submit; you could also validate a field on blur.
  • To add a new field type, add a union member, a validation case and a render case. TypeScript reports every place you forget (Lesson 108).

Component registries

For dashboards and page builders, map type names in the config to components:

TSX
type WidgetConfig = { type: "stat" | "text"; props: Record<string, string> };

const WIDGETS: Record<WidgetConfig["type"], (props: Record<string, string>) => ReactNode> = {
  stat: (p) => <div className="stat"><strong>{p.value}</strong> {p.label}</div>,
  text: (p) => <p>{p.body}</p>
};

function Dashboard2({ widgets }: { widgets: WidgetConfig[] }) {
  return <>{widgets.map((w, i) => <section key={i}>{WIDGETS[w.type](w.props)}</section>)}</>;
}

(Here the index key is acceptable only because the list is static. With reorderable widgets, give each widget an ID.)

Trade-offs

BenefitCost
Many forms or screens from one well-tested rendererHarder to handle special, one-off layouts
Non-developers or APIs can change the UI without a deployConfig must be validated (it may come from outside: Lesson 114)
Consistent accessibility and behaviour everywhereDebugging happens in data, not code
Easy to over-engineer for only two or three forms

Use it when there are many similar screens that change often. For a handful of forms, normal components are simpler.

Existing libraries: JSON Forms, react-jsonschema-form (based on the JSON Schema standard), and form builders built on React Hook Form.

How to say it in an interview

"Config-driven UI describes screens as data and renders them with one generic renderer. I model field types as a discriminated union, write validation as a pure function from the same config so it can also run on the server, and render each field with a switch on its kind, building labels, aria-invalid and aria-describedby in once for every form. For dashboards I use a registry mapping type names to components. It pays off when there are many similar screens that change often, as long as the config itself is validated, and it is over-engineering for a few forms."

Key words

WordMeaning
Config-driven UIUI generated from data instead of hand-written components
SchemaThe data describing a form or screen
RendererThe component that turns config into UI
Component registryA map from type names to components
JSON SchemaA standard format for describing JSON data

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.