Skip to Content
Piplup
@piplup/rhf-adaptersmui-materialComponents

MuiFormHelperTextElement

Use MUI FormHelperText with react-hook-form without writing a Controller. MuiFormHelperTextElement shows a field’s validation error or your hint text.

Import

import { MuiFormHelperTextElement } from '@piplup/rhf-adapters/mui-material';

Usage

'use client';import * as React from 'react';import FormControl from '@mui/material/FormControl';import Stack from '@mui/material/Stack';import {  MuiFormHelperTextElement,  MuiOutlinedInputElement,  MuiFormLabelElement,  MuiButtonElement,} from '@piplup/rhf-adapters/mui-material';import { useForm } from 'react-hook-form';export default function Page() {  const inputId = React.useId();  const helperTextId = `${inputId}-helper-text`;  const { control, handleSubmit } = useForm({ defaultValues: { email: '' } });  return (    <form onSubmit={handleSubmit((values) => alert(JSON.stringify(values, null, 2)))} noValidate>      <Stack direction="column" spacing={2}>        <FormControl variant="outlined">          <MuiFormLabelElement control={control} htmlFor={inputId} name="email" sx={{ mb: 0.5 }}>            Email          </MuiFormLabelElement>          <MuiOutlinedInputElement            aria-describedby={helperTextId}            control={control}            id={inputId}            name="email"            type="email"            required          />          <MuiFormHelperTextElement            control={control}            id={helperTextId}            name="email"            renderOnError          />        </FormControl>        <div>          <MuiButtonElement control={control} type="submit" variant="contained">            Submit          </MuiButtonElement>        </div>      </Stack>    </form>  );}

Props

Prop

Type

MuiFormHelperTextElement supports all standard props of the MUI FormHelperText component, along with additional adapter-specific props. For a complete list of available FormHelperText properties, refer to the MUI API documentation.

The ref is forwarded to the underlying <FormHelperText /> component.

useMuiFormHelperTextAdapter

useMuiFormHelperTextAdapter returns props for MUI's FormHelperText that show the validation message of a field registered by another hook. It's what MuiFormHelperTextElement uses internally.

Use the hook when the message is part of a custom field component, or when you want control the element doesn't give you: your own markup for the message, a different place in the layout, or your own rule for when it renders.

Import

import { useMuiFormHelperTextAdapter } from '@piplup/rhf-adapters/mui-material';

PhoneField uses useMuiInputBaseAdapter for the input. PhoneError is a separate component that reads the same field's error, formats it with an errorParser, and renders nothing while the field is valid. Submit empty, then type letters, to see both messages.

'use client';import * as React from 'react';import FormHelperText from '@mui/material/FormHelperText';import InputBase from '@mui/material/InputBase';import Stack from '@mui/material/Stack';import Typography from '@mui/material/Typography';import {  MuiButtonElement,  useMuiFormHelperTextAdapter,  useMuiInputBaseAdapter,} from '@piplup/rhf-adapters/mui-material';import { useForm } from 'react-hook-form';import type { Control, FieldError } from 'react-hook-form';type FormValues = { phone: string };// An error-only helper text with its own formatting. It reads the field's// error by name; the input itself does not render any helper text.function PhoneError({ control, id }: { control: Control<FormValues>; id: string }) {  const helper = useMuiFormHelperTextAdapter<FormValues, 'phone', HTMLParagraphElement>({    composeHelperText: true,    control,    errorParser: (error) => {      const message = (error as FieldError | undefined)?.message;      return message ? <strong>{message}</strong> : null;    },    name: 'phone',  });  if (!helper.error) {    return null;  }  return <FormHelperText {...helper} id={id} role="alert" />;}function PhoneField({ control }: { control: Control<FormValues> }) {  const inputId = React.useId();  const errorId = `${inputId}-error`;  const { helperText, ref, ...input } = useMuiInputBaseAdapter({    control,    messages: {      pattern: 'Use digits and spaces, with an optional leading +',      required: 'Add a phone number so the courier can reach you',    },    name: 'phone',    pattern: /^\+?[0-9 ]{7,15}$/,    required: true,    type: 'tel',  });  return (    <Stack spacing={0.5}>      <Typography component="label" htmlFor={inputId} variant="body2">        Phone for delivery      </Typography>      <InputBase        {...input}        sx={{          border: 1,          borderColor: input.error ? 'error.main' : 'divider',          borderRadius: 1,          px: 1.5,          py: 0.5,        }}        id={inputId}        inputRef={ref}        slotProps={{ input: { 'aria-describedby': errorId } }}      />      <PhoneError control={control} id={errorId} />    </Stack>  );}export default function Page() {  const { control, handleSubmit } = useForm<FormValues>({    defaultValues: { phone: '' },  });  return (    <form onSubmit={handleSubmit((values) => alert(JSON.stringify(values, null, 2)))} noValidate>      <Stack direction="column" spacing={2}>        <PhoneField control={control} />        <div>          <MuiButtonElement control={control} type="submit" variant="contained">            Continue          </MuiButtonElement>        </div>      </Stack>    </form>  );}

How it works

The hook reads the field's state by name and registers nothing, like useMuiFormLabelAdapter. It returns children, error, disabled, className, style, classes and ref, all of which FormHelperText accepts, so the result can be spread as is.

Children and the error message. You pass the normal text as children. What comes back as children depends on composeHelperText:

composeHelperTextField validField invalid
not set (default)your childrenyour children (only error changes)
trueyour childrenthe error message

The element always sets composeHelperText: true; the hook doesn't. If the error has no message, your children are shown.

Showing it only on error. The element's renderOnError prop isn't part of the hook. Check error yourself and return null, as PhoneError does.

Formatting the message. By default the message is error.message when it's a string. Pass errorParser to return any React node instead. It receives the field's error object, or undefined when there is none.

A parser from FormErrorProvider takes priority over the errorParser you pass to this hook. Inside a provider, your per-field parser is ignored.

Accessibility. The hook doesn't link the message to the input. Give FormHelperText an id and point the input's aria-describedby at it, as the demo does.

Props

Prop

Type

Return value

Prop

Type

See also

On this page