RHFTextField
RHFTextField extends the Material UI
TextField component, accepting
almost all of its props. It binds the field to React Hook Form through
control, so the value, validation state and error message come straight from
your form, with no value or onChange wiring on your side.
For specialized inputs, you can also use RHFPasswordInput for password values or RHFNumberInput for numeric input.
Usage
import RHFTextField, { RHFTextFieldProps } from '@nish1896/rhf-mui-components/mui/textfield';Pass the control returned by useForm and the fieldName to bind. That is
all you need to render a fully functional text field:
import { useForm } from 'react-hook-form';
type FormValues = {
firstName: string;
};
const { control, handleSubmit } = useForm<FormValues>({
defaultValues: { firstName: '' }
});
<form onSubmit={handleSubmit(values => console.log(values))}>
<RHFTextField
fieldName="firstName"
control={control}
/>
</form>fieldName is typed against your form values, so a misspelled field name is a
compile-time error.
Customizing the label
By default, the label is generated from fieldName, so firstName becomes
"First Name". Use label to override it with any ReactNode.
showLabelAboveFormField renders the label above the input instead of inside
it, and hideLabel removes the visible label while keeping an accessible one.
formLabelProps is forwarded to the label, for example to style it with sx.
<RHFTextField
fieldName="email"
control={control}
label="Work email"
showLabelAboveFormField
formLabelProps={{
sx: { fontWeight: 600 }
}}
helperText="We never share your email"
formHelperTextProps={{
sx: { fontStyle: 'italic' }
}}
/>To place every label above its field at once, use allLabelsAboveFields in
ConfigProvider.
Validation
Validation rules go in registerOptions, the same object you would pass to
register in React Hook Form. The field reads its error state from the form, so
there is no error message to derive or keep in sync: when a rule fails, the
field switches to an error state and shows the message below the input.
required is derived from registerOptions.required, so the label gets its
required marker automatically. Pass required explicitly only when you want the
marker without a required rule.
<RHFTextField
fieldName="username"
control={control}
registerOptions={{
required: 'Username is required',
minLength: { value: 3, message: 'Use at least 3 characters' },
maxLength: { value: 16, message: 'Use at most 16 characters' }
}}
/>Using a regex
Use the pattern rule for format checks:
<RHFTextField
fieldName="username"
control={control}
registerOptions={{
pattern: {
value: /^[a-z0-9_]{3,16}$/,
message: 'Use 3-16 lowercase letters, digits or underscores'
}
}}
/>By default React Hook Form validates on submit and then re-validates on every
change. Use the mode option of useForm (onBlur, onChange, onTouched)
to validate earlier.
Custom rules
validate accepts a function that returns true when the value is valid, or a
message when it is not. It can be async, which suits checks against a server:
<RHFTextField
fieldName="email"
control={control}
registerOptions={{
required: 'Email is required',
validate: async value =>
(await isEmailAvailable(value)) || 'This email is already registered'
}}
/>Validation with a schema
Instead of per-field rules you can hand validation to a schema library through a
resolver, for example zodResolver, yupResolver or joiResolver from
@hookform/resolvers. Errors from the schema land on the same field and render
the same way.
const { control } = useForm<FormValues>({
resolver: zodResolver(schema)
});Showing multiple errors
By default only the first failing rule is reported. Set criteriaMode: 'all' in
useForm to collect every failing rule, and read them from error.types in
renderError. Give each validate rule its own key so each message has a
name:
const { control } = useForm<FormValues>({
criteriaMode: 'all'
});
<RHFTextField
fieldName="password"
control={control}
registerOptions={{
validate: {
uppercase: value => /[A-Z]/.test(value) || 'Add an uppercase letter',
digit: value => /\d/.test(value) || 'Add a digit',
length: value => value.length >= 8 || 'Use at least 8 characters'
}
}}
renderError={error => (
<ul style={{ margin: 0, paddingLeft: 16 }}>
{Object.values(error.types ?? {}).map(message => (
<li key={String(message)}>{String(message)}</li>
))}
</ul>
)}
/>renderError receives the FieldError and can return anything renderable, so
it also works for a single message, an icon next to the text, or a link.
hideErrorMessage keeps the field in an error state without showing any text.
helperText is shown while there is no visible error.
Handling value changes
onValueChange runs after the new value has been stored in the form. It
receives { newValue, event }:
<RHFTextField
fieldName="search"
control={control}
onValueChange={({ newValue, event }) => {
runSearch(newValue)
}}
/>Use customOnChange when you need to change what gets stored. It replaces the
default handling, so you must call rhfOnChange yourself with the value to
store. This example stores the text capitalized:
<RHFTextField
fieldName="firstName"
control={control}
customOnChange={({ rhfOnChange, newValue, event }) => {
rhfOnChange(newValue.toUpperCase());
}}
/>onValueChange is not called when customOnChange is used.
Disabling the field
Pass disabled to disable a single field. A form-level disabled option on
useForm is respected too, and disables every field that supports it:
const { control } = useForm<FormValues>({ disabled: isSubmitting });Disabled fields follow React Hook Form behavior, so depending on how you serialize the form their values may be left out of the submitted payload.
Wrapping the component
You can extend or reuse the RHFTextField component by creating your own
wrapper component.
/**
* The below code snippet illustrates how to create a reusable styled Textfield
* component using RHFTextField, which can be used throughout the application.
*
* In this example, the component accepts all the props of RHFTextField except
* 'renderError', 'variant' and 'showLabelAboveFormField', which have already
* been configured to maintain consistent styling across the application.
* Additionally, it includes a custom error message component that displays an
* error icon alongside the error message when there is an error.
*
* A similar approach can be taken to create reusable styled components for:
* - RHFNumberInput
* - RHFTagsInput
* - RHFPasswordInput
*/
import { Fragment, type ReactNode } from 'react';
import { type FieldValues } from 'react-hook-form';
import Typography from '@mui/material/Typography';
import RHFTextField, { type RHFTextFieldProps } from '@nish1896/rhf-mui-components/mui/textfield';
import PriorityHighIcon from '@mui/icons-material/PriorityHigh';
type StyledRHFTextFieldProps<T extends FieldValues> = Omit<
RHFTextFieldProps<T>,
'renderError' | 'showLabelAboveFormField' | 'variant'
>;
type StyledErrorMsgProps = {
errorMessage: ReactNode;
};
const StyledErrorMsg = ({ errorMessage }: StyledErrorMsgProps) => {
return (
<Fragment>
{!!errorMessage && (
<Typography
variant="body2"
sx={{
alignItems: 'center',
display: 'flex',
gap: 0.5
}}
>
<PriorityHighIcon color="error" fontSize="small" />
{errorMessage}
</Typography>
)}
</Fragment>
);
};
const StyledRHFTextField = <T extends FieldValues>(
props: StyledRHFTextFieldProps<T>
) => {
const { formHelperTextProps, ...rest } = props;
const {
sx: helperTextSx,
...otherFormHelperTextProps
} = formHelperTextProps ?? {};
const helperTextSxList = Array.isArray(helperTextSx)
? helperTextSx
: [];
if (helperTextSx && !Array.isArray(helperTextSx)) {
helperTextSxList.push(helperTextSx);
}
return (
<RHFTextField
{...rest}
variant="standard"
showLabelAboveFormField
formHelperTextProps={{
...otherFormHelperTextProps,
sx: [
...helperTextSxList,
{ ml: 0 }
]
}}
renderError={error => (
<StyledErrorMsg errorMessage={error?.message} />
)}
/>
);
};
export default StyledRHFTextField;
Examples
API
The RHFTextFieldProps interface extends
TextFieldProps and includes the
following additional props. Props marked with * are required.
| Name | Type | Description |
|---|---|---|
fieldName* | string | Name of the field registered with React Hook Form. This prop is required for all components. |
control* | UseFormControl | |
registerOptions | RegisterOptions | React Hook Form validation rules. Useful when not using a schema validation library such as Yup or Joi. |
customOnChange | ({ rhfOnChange, newValue, event }) => void | Override the default onChange behavior of the input. You must pass the updated newValue to the rhfOnChange function to update the field value. |
onValueChange | ({ newValue, event }) => void | Callback function triggered when the field value changes. |
label | ReactNode | The text to render in the FormLabel component. By default, the value of fieldName is transformed (e.g., "firstName" to "First Name") using the fieldNameToLabel function. |
showLabelAboveFormField | boolean | Render form label above the form field in FormLabel component. |
formLabelProps | FormLabelProps | FormLabelProps to customise FormLabel component for a field. Multiple fields can be configured using the ConfigProvider component. |
hideLabel | boolean | Hides the FormLabel component if you don’t want to display the default form label component or prefer to render a fully custom label instead. |
renderError | (error: FieldError) => ReactNode | Custom renderer for the React Hook Form field error. Receives the current field error and returns the content to display, such as error.message or a custom React element in the HelperText component.Added in v4.1.0. |
hideErrorMessage | boolean | A flag to prevent replacement of helper text of a field by the errorMessage when the validation is triggered. |
helperText | ReactNode | The content to display within the FormHelperText component below the field. If the field validation fails, this content will be overridden by the corresponding error message. |
formHelperTextProps | FormHelperTextProps | FormHelperTextProps to customise FormHelperText component for a field. Multiple fields can be configured using the ConfigProvider component. |
customIds | { field, label, helperText, error } | Overrides the default field, label, helper text, and error IDs used for accessibility. |
Source Code
View the full implementation of this component on GitHub.

