Skip to content
Open Cloud

Material UI ​

Map Material UI inputs to Formhaus field types with mapControls and pass the map to the components prop of FormRenderer.

Open in StackBlitz · Source

Install ​

bash
npm install @formhaus/core @formhaus/react @mui/material @emotion/react @emotion/styled

Component map ​

mapControls maps one MUI control per field type. MUI TextField renders its own label, helper and error, so text inputs have no shell:

tsx
import type { FieldComponentMap, FieldProps } from '@formhaus/react';
import { type ControlOption, mapControls } from '@formhaus/react/controls';
import Box from '@mui/material/Box';
import Checkbox from '@mui/material/Checkbox';
import FormControlLabel from '@mui/material/FormControlLabel';
import MenuItem from '@mui/material/MenuItem';
import Radio from '@mui/material/Radio';
import RadioGroup from '@mui/material/RadioGroup';
import Rating from '@mui/material/Rating';
import Switch from '@mui/material/Switch';
import TextField from '@mui/material/TextField';
import { Fragment } from 'react';
import { AutocompleteField } from './fields/AutocompleteField';
import { MatrixRow } from './fields/MatrixRow';
import { ImageTiles, Segment } from './fields/options';
import { describedBy, FilePicker, FileShell, GroupShell, InlineShell, labels } from './fields/shells';

const menu = (options: ControlOption[]) =>
  options.map((option) => (
    <MenuItem key={option.value} value={option.value}>
      {option.label}
    </MenuItem>
  ));

const radios = (f: FieldProps, options: ControlOption[]) =>
  options.some((option) => option.image)
    ? { sx: { display: 'block' }, children: <ImageTiles options={options} value={f.value} /> }
    : {
        children: options.map((option) => (
          <Fragment key={option.value}>
            <FormControlLabel
              value={option.value}
              control={<Radio inputProps={{ 'aria-controls': option.reveal?.id }} />}
              label={option.label}
            />
            {option.reveal && (
              <Box
                id={option.reveal.id}
                data-fh="reveal"
                hidden={!option.reveal.open}
                sx={{ ml: 1.25, pl: 2.25, borderLeft: 2, borderColor: 'divider' }}
              >
                {option.reveal.children}
              </Box>
            )}
          </Fragment>
        )),
      };

const points = (options: ControlOption[]) =>
  options.map((option) => (
    <Radio
      key={option.value}
      value={option.value}
      icon={<Segment label={option.label} />}
      checkedIcon={<Segment label={option.label} checked />}
      inputProps={{ 'aria-label': option.label }}
      disableRipple
      sx={{ flex: 1, p: 0, borderRadius: 0, '& + &': { ml: '-1px' } }}
    />
  ));

export const components: FieldComponentMap = {
  ...mapControls({
    shell: { input: null, inline: InlineShell, group: GroupShell },
    labels,
    kinds: { multiselect: 'input' },
    matrix: MatrixRow,
    freeText: true,
    conditionalReveal: ['radio'],
    controls: {
      input: TextField,
      textarea: { component: TextField, props: () => ({ multiline: true }) },
      select: { component: TextField, props: (_, options) => ({ select: true, children: menu(options) }) },
      multiselect: {
        component: TextField,
        props: (f, options) => ({
          select: true,
          slotProps: { ...labels(f).slotProps, select: { multiple: true } },
          children: menu(options),
        }),
      },
      checkbox: { component: Checkbox, props: (f) => ({ inputProps: { ...f.aria, 'aria-describedby': describedBy(f) } }) },
      switch: { component: Switch, props: (f) => ({ inputProps: { ...f.aria, 'aria-describedby': describedBy(f) } }) },
      radio: { component: RadioGroup, props: radios },
      scale: { component: RadioGroup, props: (_, options) => ({ row: true, sx: { flexWrap: 'nowrap' }, children: points(options) }) },
      rating: {
        component: Rating,
        props: (_, options) => ({ max: options.length, size: 'large', 'aria-required': undefined, 'aria-invalid': undefined }),
      },
      autocomplete: {
        component: AutocompleteField,
        props: (_, options) => ({ options: options.map((option) => option.label) }),
        changeProp: 'onInputChange',
      },
    },
  }),
  ...mapControls({
    shell: FileShell,
    controls: {
      file: {
        component: FilePicker,
        props: (f, _, { field }) => ({ f, field, 'aria-labelledby': `${f.id}-label ${f.id}-button`, 'aria-describedby': describedBy(f) }),
      },
    },
  }),
};

Shells ​

Checkbox, switch, the choice groups and the file picker get a FormControl shell:

tsx
import type { FormField } from '@formhaus/core';
import { fileEntries, filesFull, pickFiles, removeFile } from '@formhaus/core/fields';
import type { FieldProps } from '@formhaus/react';
import type { ControlShellProps } from '@formhaus/react/controls';
import Box from '@mui/material/Box';
import Button, { type ButtonProps } from '@mui/material/Button';
import FormControl from '@mui/material/FormControl';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormHelperText from '@mui/material/FormHelperText';
import FormLabel from '@mui/material/FormLabel';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import Typography from '@mui/material/Typography';
import { styled } from '@mui/material/styles';
import { type InputHTMLAttributes, type ReactElement, useState } from 'react';

const helper = (f: FieldProps) =>
  f.maxLength ? (
    <Box component="span" sx={{ display: 'flex', justifyContent: 'space-between', gap: 2 }}>
      <span>{f.error ?? f.helperText}</span>
      <span>
        {f.text.length}/{f.maxLength}
      </span>
    </Box>
  ) : (
    (f.error ?? f.helperText)
  );

export const labels = (f: FieldProps) => ({
  label: f.label,
  required: f.required,
  error: f.invalid,
  helperText: helper(f),
  fullWidth: true,
  margin: 'normal' as const,
  'data-testid': undefined,
  slotProps: {
    inputLabel: { shrink: f.inputType.includes('date') || f.inputType === 'time' || undefined },
    htmlInput: { 'data-testid': f.testId },
  },
});

export const describedBy = (f: FieldProps) => (f.error ? f.errorId : f.helperText ? f.helperId : undefined);

export function Texts({ f }: Pick<ControlShellProps, 'f'>) {
  const text = f.error ?? f.helperText;
  return text ? <FormHelperText id={f.error ? f.errorId : f.helperId}>{text}</FormHelperText> : null;
}

export function InlineShell({ f, rootProps, children }: ControlShellProps) {
  return (
    <FormControl {...rootProps} variant="standard" error={f.invalid} sx={{ mt: 1, mb: 0.5 }}>
      <FormControlLabel control={children as ReactElement} label={f.label} required={f.required} />
      <Texts f={f} />
    </FormControl>
  );
}

export function GroupShell({ field, f, rootProps, anchors, children }: ControlShellProps) {
  const inline = field.layout === 'inline' && { '& > .MuiFormGroup-root': { flexDirection: 'row', flexWrap: 'wrap' } };
  return (
    <FormControl
      {...rootProps}
      aria-describedby={describedBy(f)}
      component="fieldset"
      variant="standard"
      error={f.invalid}
      fullWidth
      sx={{ mt: 1, mb: 0.5, ...inline }}
    >
      <FormLabel component="legend" required={f.required} sx={{ mb: 0.5 }}>
        {f.label}
      </FormLabel>
      {children}
      {anchors.some(Boolean) && (
        <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 0.5 }}>
          {anchors.map((anchor, index) => (
            <Typography key={index} variant="caption" color="text.secondary">
              {anchor?.label}
            </Typography>
          ))}
        </Box>
      )}
      <Texts f={f} />
    </FormControl>
  );
}

export function FileShell({ f, rootProps, children }: ControlShellProps) {
  return (
    <FormControl {...rootProps} variant="standard" error={f.invalid} margin="normal">
      <FormLabel id={`${f.id}-label`} required={f.required} sx={{ mb: 0.5 }}>
        {f.label}
      </FormLabel>
      {children}
      <Texts f={f} />
    </FormControl>
  );
}

const HiddenInput = styled('input')({
  clip: 'rect(0 0 0 0)',
  clipPath: 'inset(50%)',
  height: 1,
  overflow: 'hidden',
  position: 'absolute',
  bottom: 0,
  left: 0,
  whiteSpace: 'nowrap',
  width: 1,
});

type FilePickerProps = ButtonProps<'label'> &
  Pick<InputHTMLAttributes<HTMLInputElement>, 'name' | 'accept' | 'multiple' | 'onChange'> & {
    f: FieldProps;
    field: FormField;
    'aria-required'?: boolean;
    'aria-invalid'?: boolean;
    'aria-describedby'?: string;
    'data-testid'?: string;
  };

const visuallyHidden = {
  position: 'absolute',
  width: 1,
  height: 1,
  overflow: 'hidden',
  clip: 'rect(0 0 0 0)',
  whiteSpace: 'nowrap',
} as const;

export function FilePicker({ f, field, id, name, accept, multiple, onChange, disabled, 'data-testid': testId, ...aria }: FilePickerProps) {
  const [file, setFile] = useState('');
  const [notice, setNotice] = useState('');
  const [status, setStatus] = useState('');
  const full = multiple && filesFull(field, f.value);
  const entries = multiple ? fileEntries(f.value) : [];
  return (
    <>
      <Box sx={{ display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: 1.5 }}>
        <Button
          component="label"
          id={`${id}-button`}
          variant="outlined"
          disabled={disabled || full}
          sx={{ '&:focus-within': { outline: 2, outlineColor: 'primary.main', outlineOffset: 2 } }}
        >
          {multiple ? 'Add files' : 'Choose file'}
          <HiddenInput
            id={id}
            type="file"
            name={name}
            accept={accept}
            multiple={multiple}
            disabled={disabled || full}
            data-testid={testId}
            aria-labelledby={aria['aria-labelledby']}
            aria-describedby={aria['aria-describedby']}
            aria-invalid={aria['aria-invalid']}
            aria-required={aria['aria-required']}
            onChange={(event) => {
              if (!multiple) {
                setFile(event.target.files?.[0]?.name ?? '');
                return onChange?.(event);
              }
              const picked = Array.from(event.target.files ?? []);
              event.target.value = '';
              if (!picked.length) return;
              const result = pickFiles(field, f.value, picked);
              if (result.value) f.change(result.value);
              setNotice(result.notice);
              setStatus(result.status);
            }}
          />
        </Button>
        {file && <Typography variant="body2">{file}</Typography>}
      </Box>
      {entries.length > 0 && (
        <List dense disablePadding sx={{ mt: 1 }}>
          {entries.map(({ index, name }) => (
            <ListItem
              key={index}
              divider
              disableGutters
              secondaryAction={
                <Button
                  size="small"
                  color="error"
                  aria-label={`Remove ${name}`}
                  disabled={disabled}
                  onClick={() => {
                    setNotice('');
                    f.change(removeFile(f.value, index));
                    setStatus(`${name} removed`);
                  }}
                >
                  Remove
                </Button>
              }
            >
              <ListItemText primary={name} slotProps={{ primary: { dir: 'auto', sx: { overflowWrap: 'anywhere' } } }} />
            </ListItem>
          ))}
        </List>
      )}
      {notice && <FormHelperText>{notice}</FormHelperText>}
      {multiple && (
        <Box role="status" sx={visuallyHidden}>
          {status}
        </Box>
      )}
    </>
  );
}

Autocomplete ​

MUI Autocomplete needs renderInput, so a small freeSolo wrapper is mapped as the autocomplete control with freeText: true:

tsx
import Autocomplete from '@mui/material/Autocomplete';
import TextField, { type TextFieldProps } from '@mui/material/TextField';
import type { SyntheticEvent } from 'react';

type AutocompleteFieldProps = TextFieldProps & {
  options: string[];
  value: string;
  onInputChange: (event: SyntheticEvent, value: string) => void;
};

export function AutocompleteField({
  id,
  options,
  value,
  onInputChange,
  onBlur,
  onFocus,
  disabled,
  slotProps,
  ...field
}: AutocompleteFieldProps) {
  return (
    <Autocomplete
      freeSolo
      forcePopupIcon
      fullWidth
      id={id}
      options={options}
      value={value}
      inputValue={value}
      onInputChange={onInputChange}
      disabled={disabled}
      renderInput={({ inputProps, InputProps, InputLabelProps, ...params }) => (
        <TextField
          {...params}
          {...field}
          slotProps={{ input: InputProps, inputLabel: InputLabelProps, htmlInput: { ...inputProps, ...slotProps?.htmlInput } }}
        />
      )}
    />
  );
}

App ​

tsx
import { parseDefinition, type FormDefinition } from '@formhaus/core';
import { FormRenderer } from '@formhaus/react';
import { Container, CssBaseline, ThemeProvider, Typography, createTheme } from '@mui/material';
import { useMemo, useState } from 'react';
import { FormActions } from './actions/FormActions';
import { ErrorSummary } from './actions/ErrorSummary';
import { Fields } from './actions/Fields';
import { ConfirmDialog, Group, GroupItem } from './actions/Groups';
import { Section } from './actions/Section';
import { StepProgress } from './actions/StepProgress';
import { FormCompletion } from './FormCompletion';
import { components } from './component-map';
import json from './definition.json';

const layout = {
  actions: FormActions,
  progress: StepProgress,
  section: Section,
  errorSummary: ErrorSummary,
  fields: Fields,
  group: Group,
  groupItem: GroupItem,
  confirmDialog: ConfirmDialog,
};

const initial = parseDefinition(json);

export default function App({ definition = initial, mode = 'light' }: { definition?: FormDefinition; mode?: 'light' | 'dark' }) {
  const [submitted, setSubmitted] = useState<Record<string, unknown> | null>(null);
  const theme = useMemo(() => createTheme({ palette: { mode } }), [mode]);

  return (
    <ThemeProvider theme={theme}>
      <CssBaseline enableColorScheme />
      <Container maxWidth={false} sx={{ maxWidth: 648, py: 4 }}>
        {submitted ? (
          <FormCompletion definition={definition} values={submitted} onRestart={() => setSubmitted(null)} />
        ) : (
          <>
            {definition.title && (
              <Typography variant="h5" component="h1" gutterBottom>
                {definition.title}
              </Typography>
            )}
            <FormRenderer definition={definition} components={components} layout={layout} conditionalReveal onSubmit={setSubmitted} />
          </>
        )}
      </Container>
    </ThemeProvider>
  );
}

The option tiles and the matrix row are in src/fields, the layout slots in src/actions.

Server validation ​

The example validates in the browser only. On the server, run validateSubmission() from @formhaus/core/server on the posted values and pass the returned errors to the errors prop. See Server-side validation and Next.js for a complete route handler.