Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 36 · Projects and Practice

Project: Settings Form

Build a settings page with Material UI: TextField validation, Switch, Select, dirty tracking, a save button with loading state and a Snackbar, with a runnable stand-in.

Forms are the other half of most apps. In this project you will build a profile and notification settings page with the pieces that make a form feel finished: labels and helper text, inline validation, a switch group, a select, a Save button that is disabled until something changes, a loading state while saving, and a confirmation message.

Material UI cannot run in the live editors on this site. The steps show real MUI code read-only; the runnable preview is a stand-in with the same state logic and structure, so you can run and change the validation and save flow.

Plan the state

Keep the form state in one object, keep the saved values beside it, and derive the rest:

  • values: what the fields currently show,
  • saved: the last values stored on the server,
  • touched: which fields the user has visited (to show errors only after interaction),
  • errors: computed from values with a pure validate function,
  • dirty: values differ from saved,
  • status: 'idle', 'saving' or 'saved'.
TSX
// Real Material UI + TypeScript, read-only
type Settings = {
  name: string;
  email: string;
  language: 'en' | 'de' | 'fr';
  bio: string;
  newsletter: boolean;
  productUpdates: boolean;
};

type Errors = Partial<Record<keyof Settings, string>>;

export function validate(v: Settings): Errors {
  const errors: Errors = {};
  if (v.name.trim().length < 2) {
    errors.name = 'Enter at least 2 characters.';
  }
  if (!/^\S+@\S+\.\S+$/.test(v.email)) {
    errors.email = 'Enter an email address like [email protected].';
  }
  if (v.bio.length > 160) {
    errors.bio = `${v.bio.length - 160} characters too long.`;
  }
  return errors;
}

Validation is a pure function: easy to test, and the same function can run again on the server.

The fields

TSX
// Real Material UI, read-only
<Stack component="form" spacing={3} onSubmit={handleSubmit} noValidate sx={{ maxWidth: 520 }}>
  <TextField
    label="Display name"
    value={values.name}
    onChange={(e) => setField('name', e.target.value)}
    onBlur={() => touch('name')}
    error={touched.name && Boolean(errors.name)}
    helperText={touched.name && errors.name ? errors.name : 'Shown on your public profile'}
    required
  />

  <TextField
    label="Email"
    type="email"
    value={values.email}
    onChange={(e) => setField('email', e.target.value)}
    onBlur={() => touch('email')}
    error={touched.email && Boolean(errors.email)}
    helperText={touched.email && errors.email}
    slotProps={{ htmlInput: { autoComplete: 'email' } }}
    required
  />

  <TextField
    select
    label="Language"
    value={values.language}
    onChange={(e) => setField('language', e.target.value as Settings['language'])}
  >
    <MenuItem value="en">English</MenuItem>
    <MenuItem value="de">Deutsch</MenuItem>
    <MenuItem value="fr">Français</MenuItem>
  </TextField>

  <TextField
    label="Bio"
    multiline
    minRows={3}
    value={values.bio}
    onChange={(e) => setField('bio', e.target.value)}
    error={Boolean(errors.bio)}
    helperText={errors.bio ?? `${values.bio.length}/160`}
  />

  <FormControl component="fieldset" variant="standard">
    <FormLabel component="legend">Notifications</FormLabel>
    <FormGroup>
      <FormControlLabel
        control={<Switch checked={values.newsletter} onChange={(e) => setField('newsletter', e.target.checked)} />}
        label="Weekly newsletter"
      />
      <FormControlLabel
        control={<Switch checked={values.productUpdates} onChange={(e) => setField('productUpdates', e.target.checked)} />}
        label="Product updates"
      />
    </FormGroup>
  </FormControl>

  <Stack direction="row" spacing={2}>
    <Button type="submit" variant="contained" disabled={!dirty || status === 'saving'}
      startIcon={status === 'saving' ? <CircularProgress size={16} /> : null}>
      {status === 'saving' ? 'Saving...' : 'Save changes'}
    </Button>
    <Button onClick={reset} disabled={!dirty}>Discard</Button>
  </Stack>
</Stack>

Details that matter:

  • noValidate turns off the browser's own popups so MUI's inline messages are the only ones. Keep required for the asterisk and for assistive technology.
  • Show errors after onBlur (or after a submit attempt), not while the user is still typing the first character.
  • Reserve the helper text line (use an empty string or a hint) to avoid layout jumps when an error appears. MUI's TextField keeps the space if you pass helperText=" ".
  • A group of related switches or checkboxes needs a fieldset with a legend, which FormControl component="fieldset" and FormLabel component="legend" provide.
  • select on TextField renders a MUI Select with the label linked; use MenuItem children.
  • Add autoComplete values so the browser can fill known data.

Submitting

TSX
// Real Material UI, read-only
async function handleSubmit(event: React.FormEvent) {
  event.preventDefault();
  setTouchedAll();
  if (Object.keys(errors).length > 0) {
    focusFirstInvalid();
    return;
  }
  setStatus('saving');
  try {
    await api.saveSettings(values);   // your request
    setSaved(values);
    setStatus('saved');
    setToast({ severity: 'success', text: 'Settings saved' });
  } catch {
    setStatus('idle');
    setToast({ severity: 'error', text: 'Could not save. Try again.' });
  }
}

On failed validation move focus to the first invalid field, so keyboard and screen reader users land where the problem is.

Try it: the settings form

The stand-in follows the plan: pure validate, touched fields, dirty tracking, a fake asynchronous save and a toast. Try an invalid email, leave a field and watch the error, change something and see Save enable, then save.

Settings form with validation, dirty state and toast

Warn before leaving

A dirty form should not vanish on an accidental navigation. In the browser, add a beforeunload handler while dirty is true; with a router, use its navigation blocker. The React Router lesson on blocking navigation shows both. Prefer autosave or a "draft" for long forms; it removes the problem.

Using a form library

State in one component is fine for ten fields. For longer or more complex forms, use React Hook Form (uncontrolled inputs, fewer re-renders) with a validation schema such as Zod, and connect MUI's controlled TextField through its Controller component:

TSX
// Real React Hook Form + Material UI, read-only
<Controller
  name="email"
  control={control}
  rules={{ required: 'Email is required' }}
  render={({ field, fieldState }) => (
    <TextField {...field} label="Email" error={!!fieldState.error} helperText={fieldState.error?.message} />
  )}
/>

Improve it

  1. Add a password-change section with a show/hide toggle (InputAdornment plus IconButton with aria-label).
  2. Disable the language select while saving.
  3. Validate on the server too: show a server error under the email field when the address is taken.
  4. Add an avatar upload with a preview and file size validation.
  5. Write Testing Library tests: error appears after blur, Save is disabled until a change, success message after save.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. When should an inline error normally appear?

    Showing errors too early is distracting. After blur or a submit attempt, the user has finished typing.
  2. 2. Why use a fieldset with a legend for a group of switches?

    Related controls are grouped with fieldset and legend. MUI provides FormControl component="fieldset" with FormLabel component="legend".
  3. 3. What is a benefit of a pure validate(values) function?

    A pure function has no side effects, so the same rules can be tested in isolation and run in both places.
  4. 4. What should happen when a user submits an invalid form?

    Showing every error and focusing the first one helps all users, especially keyboard and screen reader users.

Summary

  • Keep values, saved, touched and a status; derive errors and dirty.
  • Validate with a pure function; show errors after blur or submit; focus the first invalid field.
  • Group switches in a fieldset with a legend; disable Save until changed and while saving.
  • Confirm success with a Snackbar and warn before leaving a dirty form.

Next: Project: Data Table with Filters