Every MUI app seems to have one: the form that started as three fields and slowly became a four-step wizard. It has a section that appears only when a switch is on, a table where users add rows, fields that are required only in some cases, and a product manager who wants "just one more question" every sprint.
MUI gives you excellent inputs, but no form engine. So you assemble one: react-hook-form for state, Zod for validation, a Stepper for pages, and glue code to hold it all together. It works, and most of us have shipped forms exactly like that.
There is another way: describe the form as JSON and let a form library render it, while it still looks like the rest of your MUI app. That's what SurveyJS and its MUI theme adapter do.
To compare the two approaches honestly, I built the same multi-step form twice:
- Version A: MUI + react-hook-form + Zod, written by hand.
- Version B: SurveyJS Form Library + the MUI theme adapter.
Then I measured both, applied the same change request to each, and noted where each approach wins. Full disclosure: this post comes from the SurveyJS team. So every number below comes from a companion repo you can run and check yourself, and I'll point out where SurveyJS is the worse choice too.
SurveyJS in two minutes
If you've never used SurveyJS, three pieces matter for this post.
Form Library (survey-core + survey-react-ui, MIT-licensed). You give it a JSON schema; it renders the form at runtime and handles the behavior: pages, conditional visibility, validation, dynamic rows, input masks, localization. Your React code shrinks to "create a model, render it, handle the result". The answers come back as a plain JSON object that you send to your own API.
The MUI theme adapter. This is a stylesheet that ships with survey-core (survey-core/themes/adapters/mui.css). It also needs a one-line setup call, shown below. SurveyJS v3 styles everything through CSS variables called design tokens (--sjs2-*). The adapter points those tokens at the CSS variables MUI generates from your theme (--mui-*). So SurveyJS forms pick up your palette, typography, shape and light/dark mode, and they update live when your theme changes.
Does SurveyJS render MUI components? No, and it's worth knowing upfront. SurveyJS renders its own components; the adapter makes them look like MUI by reading your theme's variables. The upside: no coupling to MUI's component internals or version-specific APIs, and one styling system shared by everything SurveyJS renders. The trade-off: styling decisions that never reach MUI's CSS variables (an
sxprop, aGridlayout) aren't picked up automatically. More on that later.
Survey Creator (optional). Because the form is JSON, it can also be edited visually. Survey Creator is a drag-and-drop builder that produces the same JSON, so non-developers can change forms without touching code. It reuses the same tokens, so it follows your MUI theme too. You don't need it for anything in this post; if you're curious, there's a free online demo you can try in the browser.
The test form: a patient intake wizard
A login form proves nothing, so I used a realistic one: the Patient Intake form from the official SurveyJS MUI adapter demo. It has four pages:
- Patient: name, date of birth, sex, a masked phone number, preferred contact method.
- Insurance: a primary insurance group, plus a switch that reveals a required "secondary insurance" section.
- History: a yes/no/unsure grid of conditions, an allergies table where users add and remove rows (each row needs an allergen), and a free-text medications field.
- Consent: two checkboxes that must be ticked, a signature and a date.
On top of that, a progress indicator shows the pages, "Next" validates only the current page, and errors appear under the fields that caused them. Both versions implement all of it, with the same labels and error messages.
The stack: Vite, React 19, MUI 7.3, survey-core 3.2.7, react-hook-form 7.92, Zod 4. Both versions run side by side in one app shell, using the same MUI theme, behind two tabs.
Version A: MUI + react-hook-form + Zod
This is the stack most MUI developers would reach for, so I tried to write it the way a careful team would: one Zod schema, a small set of reusable field components, and one form component.
The Zod schema
The schema holds the field rules. Conditional rules, like "secondary insurance is required only when the switch is on", go into a superRefine, because they depend on more than one field:
export const patientIntakeSchema = z
.object({
firstName: required("First name is required."),
phone: z
.string()
.refine((v) => v === "" || /^\+1 \(\d{3}\) \d{3}-\d{4}$/.test(v), "Enter a complete phone number."),
hasSecondary: z.boolean(),
carrier2: z.string(),
allergies: z.array(
z.object({
allergen: required("Allergen is required."),
severity: z.enum(["Mild", "Moderate", "Severe", ""]),
reaction: z.string(),
}),
),
consentTreatment: z.boolean().refine((v) => v, "Consent to treatment is required."),
// ...15 more fields
})
.superRefine((v, ctx) => {
if (!v.hasSecondary) return;
if (!v.carrier2.trim())
ctx.addIssue({ code: "custom", path: ["carrier2"], message: "Insurance carrier is required." });
// ...same for memberId2
});
Pages and per-page validation
MUI's Stepper is purely visual, so you decide which fields belong to each page and validate only those before moving on:
const PAGES = [
{ title: "Patient", fields: ["firstName", "lastName", "dob", "phone"] },
{ title: "Insurance", fields: ["carrier", "memberId", "carrier2", "memberId2"] },
{ title: "History", fields: ["allergies"] },
{ title: "Consent", fields: ["consentTreatment", "consentPrivacy"] },
];
async function next() {
if (await trigger(PAGES[page].fields)) setPage((p) => p + 1);
}
This list has to stay in sync with the JSX: add a required field to a page and forget it here, and users can skip past it.
Conditional sections, dynamic rows and masks
The secondary insurance section uses useWatch, the allergies table uses useFieldArray, and the phone mask is a small formatting function passed to the input:
const hasSecondary = useWatch({ control, name: "hasSecondary" });
const allergies = useFieldArray({ control, name: "allergies" });
{hasSecondary && (
<Stack direction={{ xs: "column", sm: "row" }} spacing={2}>
<TextInput control={control} name="carrier2" label="Insurance carrier" required />
<TextInput control={control} name="memberId2" label="Member ID" required />
</Stack>
)}
One more detail: when the switch is turned off, the hidden values are still in the form state, so onSubmit clears them before sending anything to the server.
A bug I didn't see coming
My first version had a silent failure: on the last page, Complete did nothing. No error, no console message. The cause was the conditions grid. Each row is registered with Controller, so unanswered rows exist in the form state as undefined. My Zod schema expected "yes" | "no" | "unsure" for every row, so validation failed on fields that had no error message in the UI.
The fix was one .optional(). Tracking it down took far longer than the fix. It's a small example of the hidden coupling between schema, registered fields and UI that you maintain by hand in this approach.
The tally
Version A is 451 lines in 3 files (non-empty, non-comment lines):
| File | Lines | Reusable? |
|---|---|---|
patientIntakeSchema.ts (Zod) |
65 | no, one per form |
RhfIntake.tsx (form component) |
276 | no, one per form |
fields.tsx (Controller + MUI bindings) |
110 | yes, shared by all forms |
It's good, readable code, and you get full TypeScript inference from the Zod schema. But every page, condition and rule lives in code.
Version B: SurveyJS + the MUI theme adapter
Setup
Install the Form Library:
npm install survey-core survey-react-ui
The adapter reads MUI's CSS variables, so your theme must generate them. That's the cssVariables option in createTheme. If you already use it, there's nothing to change:
export const theme = createTheme({
cssVariables: { colorSchemeSelector: "class" }, // required by the adapter
colorSchemes: {
light: { palette: { primary: { main: "#1565c0" } } },
dark: { palette: { primary: { main: "#90caf9" } } },
},
shape: { borderRadius: 10 },
});
cssVariables: true is enough for the adapter. The colorSchemeSelector: "class" form is what you want if you switch light and dark modes with useColorScheme.
The component
This is the React side of Version B (the repo version also shows a thank-you screen after submit):
import { useEffect, useState } from "react";
import { Model, setupThemeAdapter } from "survey-core";
import { Survey } from "survey-react-ui";
import "survey-core/survey-core.css";
import "survey-core/themes/adapters/mui.css";
import { patientIntakeJson } from "./patientIntakeSchema";
// Apply the adapter's MUI layout defaults. Run once at startup, before creating any model.
setupThemeAdapter("mui");
export default function SurveyJsIntake() {
const [survey] = useState(() => new Model(patientIntakeJson));
useEffect(() => {
const onComplete = (sender: Model) => saveIntake(sender.data); // POST to your API
survey.onComplete.add(onComplete);
return () => survey.onComplete.remove(onComplete);
}, [survey]);
return <Survey model={survey} />;
}
Three details matter:
-
Order of the CSS imports. Load
survey-core.cssfirst and the adapter second, so the adapter's mappings win. -
setupThemeAdapter("mui")applies the adapter's MUI layout defaults (and aligns Survey Creator, if you use it). The CSS file does the color and font mapping; this call handles the rest. Call it once at startup, before you create any survey model. Module level, as above, is the simplest place. -
Create the model once.
useState(() => new Model(json))(oruseMemo) keeps the model, and the user's answers, across re-renders.
Render it anywhere inside your existing ThemeProvider. No extra provider is needed.
The schema
Everything else is in the JSON. Here are the parts that matched the code in Version A:
// Masked phone input: the mask also validates that the number is complete
{
type: "text",
name: "phone",
title: "Mobile phone",
inputType: "tel",
maskType: "pattern",
maskSettings: { pattern: "+1 (999) 999-9999" },
},
// Conditional section with its own required fields
{
type: "panel",
name: "secondaryInsurance",
title: "Secondary insurance",
visibleIf: "{hasSecondary} = true",
elements: [
{ type: "text", name: "carrier2", title: "Insurance carrier", isRequired: true },
{ type: "text", name: "memberId2", title: "Member ID", isRequired: true, startWithNewLine: false },
],
},
// Table where users add and remove rows
{
type: "matrixdynamic",
name: "allergies",
title: "Allergies",
addRowText: "Add allergy",
rowCount: 0,
columns: [
{ name: "allergen", title: "Allergen", cellType: "text", isRequired: true },
{ name: "severity", title: "Severity", cellType: "dropdown", choices: ["Mild", "Moderate", "Severe"] },
{ name: "reaction", title: "Reaction", cellType: "text" },
],
},
Note what isn't there: no list of fields per page, no trigger(), no useWatch, no useFieldArray, no mask function, no Stepper markup. Pages are just a pages array. "Next" validates the current page automatically. Answers to hidden questions are removed when the form is completed (the default clearInvisibleValues: "onComplete"). The phone mask both formats the input and rejects an incomplete number; by default it stores digits only, and saveMaskedValue: true keeps the formatted string.
Note on the progress indicator. The adapter styles SurveyJS's page progress bar in MUI colors, but its states don't look exactly like MUI's
Stepper. The current page is an outlined circle (MUI fills it), and completed pages keep their number (MUI shows a check mark). The logic is also different. MUI marks every page before the current one as completed. SurveyJS marks a page as completed only if it was shown, has at least one answer, and has all its required questions answered. So an optional page the user skipped without answering anything stays grey. If you need an exact match, you can restyle the states with a few CSS rules; the "completed" logic itself is SurveyJS's.
The tally
Version B is 282 lines in 2 files:
| File | Lines | Reusable? |
|---|---|---|
patientIntakeSchema.ts (JSON schema, 4.6 KB minified) |
253 | no, one per form |
SurveyJsIntake.tsx (renderer) |
29 | yes, renders any schema |
Yes, the JSON is most of it. It's still code you review and version. But it's data: it can live in a database, come from an API, or be edited in a visual builder, which matters for the next sections.
Side by side
Here's how the two versions compare on the measures I'd care about in a real project. Line counts use the same rules on both sides; bundle sizes are gzip, for each version's lazy-loaded chunk in a production build.
| MUI + react-hook-form + Zod | SurveyJS + MUI adapter | |
|---|---|---|
| Code for this form | 451 lines, 3 files | 282 lines, 2 files |
| Code for the next form | a new Zod schema + a new component | a new JSON schema |
| Where pages, conditions and rules live | Zod + JSX + page config | one JSON schema |
| Hidden-field cleanup, page validation, masks | you write them | built in |
| Who can change a form | developers | developers; non-developers via a visual builder |
| Look and feel | native MUI | follows your MUI theme, incl. dark mode |
| Layout control | anything (sx, Grid, Stack) |
design tokens + your own CSS overrides |
| Type safety | full inference from Zod | runtime schema; typing the answers is extra work |
| JS added to the bundle | ~74 KB (incl. the MUI components it uses) | ~505 KB, plus ~61 KB of CSS |
Three things stand out.
The line count gap is real but modest: about 1.6x. If you came for a "10 lines vs. 1,000 lines" headline, this isn't it. A well-factored react-hook-form version is not huge, and a complete JSON schema is not tiny. The gap grows with every additional form, because Version B's per-form cost is only the schema, but line count isn't the strongest argument either way.
The bigger difference is where the logic lives. In Version A, one rule like "secondary insurance is required when the switch is on" is spread across the Zod schema, the JSX, the page config and the submit handler. In Version B it's two properties in one place: visibleIf on the section and isRequired on its fields. The next section shows what that means when requirements change.
Bundle size is SurveyJS's weak spot. Half a megabyte of gzipped JavaScript is a lot, and you should weigh it. In practice, forms like this usually live on their own route, so load that route lazily (the companion app does, with React.lazy) and the cost is paid only by users who open the form. If your form sits on a performance-critical landing page, Version A is the better choice.
The change-request test
Forms rarely stay finished, so the most useful test is a realistic ticket:
If any allergy is marked Severe, the Reaction field becomes required, and the form asks a new question: "Do you carry an epinephrine auto-injector?" (required when shown).
I applied it to both versions. Each change is a separate commit in the repo, so you can see the full diffs.
Version A: 3 files, +29 / -3 lines
The Zod schema gets the new field and two cross-field rules:
+ carriesEpinephrine: z.enum(["yes", "no", ""]),
...
+ v.allergies.forEach((a, i) => {
+ if (a.severity === "Severe" && !a.reaction.trim())
+ ctx.addIssue({ code: "custom", path: ["allergies", i, "reaction"], message: "Describe the reaction for severe allergies." });
+ });
+ if (v.allergies.some((a) => a.severity === "Severe") && !v.carriesEpinephrine)
+ ctx.addIssue({ code: "custom", path: ["carriesEpinephrine"], message: "Response required." });
The component needs the question, a watcher to decide when to show it, an updated page config, and cleanup on submit:
- { title: "History", fields: ["allergies"] },
+ { title: "History", fields: ["allergies", "carriesEpinephrine"] },
+ const watchedAllergies = useWatch({ control, name: "allergies" });
+ const hasSevereAllergy = watchedAllergies.some((a) => a.severity === "Severe");
...
+ if (!data.allergies.some((a) => a.severity === "Severe")) {
+ data = { ...data, carriesEpinephrine: "" };
+ }
...
+ {hasSevereAllergy && (
+ <RadioInput control={control} name="carriesEpinephrine" ... />
+ )}
And a surprise: my shared RadioInput had never needed to show a validation error, so it couldn't. A shared component had to change for a one-question ticket.
Notice that the condition "has a severe allergy" is now written three times: in the schema, in the visibility check and in the submit cleanup. They must agree forever.
Version B: 1 file, +16 / -1 lines
- { name: "reaction", title: "Reaction", cellType: "text", placeholder: "Reaction" },
+ {
+ name: "reaction",
+ title: "Reaction",
+ cellType: "text",
+ placeholder: "Reaction",
+ requiredIf: "{row.severity} = 'Severe'",
+ requiredErrorText: "Describe the reaction for severe allergies.",
+ },
],
},
+ {
+ type: "boolean",
+ name: "carriesEpinephrine",
+ title: "Do you carry an epinephrine auto-injector?",
+ displayMode: "radio",
+ visibleIf: "countInArray({allergies}, 'severity', {severity} = 'Severe') > 0",
+ isRequired: true,
+ },
Each condition is written once, next to the thing it controls. Validation, visibility, the required marker and clearing the hidden answer all follow from those two expressions. No component changed. (displayMode: "radio" shows the yes/no question as radio buttons, like Version A. A boolean can also render as a segmented button, a checkbox or a switch.)
And because the change is pure data, it doesn't have to be a code change at all. If the schema is loaded from your backend, this ticket ships without a frontend deploy, and someone outside the dev team could make it in a visual builder. Whether you want that is a team decision, but it's an option Version A doesn't have.
Your theme, applied live
This is the part that makes SurveyJS usable in an MUI app at all. The adapter reads the variables MUI generates from your theme: the palette (primary, error, text, background, divider, action states), shape.borderRadius, the font family, spacing and shadows. Change any of them in createTheme, and the survey follows; there's no separate SurveyJS theme to keep in sync.
Light and dark mode work the same way. The companion app's header button is plain MUI:
const { mode, systemMode, setMode } = useColorScheme();
const isDark = (mode === "system" ? systemMode : mode) === "dark";
<Button color="inherit" onClick={() => setMode(isDark ? "light" : "dark")}>
{isDark ? "Light mode" : "Dark mode"}
</Button>
There's no SurveyJS code involved: the survey switches together with the rest of the page, keeps the user's answers, and isn't re-created.
Version A gets this for free too, of course: it is MUI. The point is that Version B doesn't stand out as "the embedded third-party widget" next to the rest of your UI.
Where the adapter stops, and how to finish the job
The adapter can only follow what MUI puts into CSS variables. Decisions you make in components never reach it:
-
sxprops andstyled()rules - layout from
Box,StackandGrid(spacing, columns, responsive breakpoints) - custom component variants and theme
componentsoverrides - your own design system built on top of MUI
So expect the colors, fonts, corners and shadows to match right away, and the spacing and a few layout conventions to need a small nudge. In my test, the most visible difference was density: SurveyJS puts 40px between questions by default, while my hand-built form used <Stack spacing={3}> (24px).
An override file you own
The fix is a small stylesheet that you load after the adapter:
import "survey-core/survey-core.css";
import "survey-core/themes/adapters/mui.css";
import "./survey-overrides.css"; // yours, loaded last
Prefer design tokens over selectors. Tokens are a stable API; SurveyJS's internal class names are less so. Matching MUI's spacing={3} is one line:
.sjs-theme-overrides {
--sjs2-layout-component-page-content-area-gap-vertical: 24px;
}
The design token reference lists the tokens for spacing, radius, typography and individual components. Use a class selector only when no token exists, and keep it narrow.
Example: error messages in a row
Here's one I hit while testing. When a short input (Date of birth) shares a row with a taller question (a radio group), SurveyJS stretches both to the same height and places the error message at the bottom of the row, well below the input. MUI developers expect helper text directly under the field. One rule fixes it:
/* Keep error messages directly under their inputs, like MUI helper text */
.sd-question__header-and-content-container {
flex-grow: 0;
}
Practical gotchas
-
Mobile layout follows the container, not the screen. SurveyJS switches to its single-column mobile layout when its own container is narrower than 600px (
--sd-mobile-width). In a two-column page or a narrow drawer, you can get the mobile layout on a desktop screen. -
Next.js. Render the survey in a client component (
"use client"). If you add Survey Creator, create it only on the client, after mount. - Heavily customized themes. If your app goes far beyond the standard MUI theme, the official MUI form builder page covers the limits, and the demo repo has a complete override file to start from.
So which one should you use?
After building both, here's my honest checklist.
Stay with react-hook-form + Zod when:
- you have a few forms that rarely change
- the form needs custom interactions or pixel-exact layouts that a schema-driven renderer would fight
- end-to-end type safety from schema to API matters more than speed of change
- the form sits on a page where every kilobyte of JavaScript counts
Consider SurveyJS + the MUI adapter when:
- you maintain many forms, or forms whose questions change every few sprints
- forms have real logic: conditional sections, dynamic rows, rules that depend on other answers
- you want to store form definitions on the server, version them, or load them per customer
- people outside the dev team should be able to adjust forms
- you want all of that without the forms looking foreign in your MUI app
The two also mix well. Nothing stops you from keeping your login and settings forms in react-hook-form and moving the long, frequently changing ones to SurveyJS.
Try it yourself
- Companion repo with both versions and the change-request commit: Try it yourself
- Live demo of the MUI adapter, with a hand-coded form next to it: mui-theme-adapter.demos.surveyjs.io
- Adapter setup guide: Theme adapters: Material UI
- Free online form builder that generates the JSON: surveyjs.io/create-free-survey





Top comments (0)