RHFTagsInput
RHFTagsInput renders a
TextField that turns typed or
pasted text into Chips. It is a
cleaner, more interactive alternative to a comma-separated text field. Add,
delete and paste actions can be intercepted, transformed or blocked, and the
visible chip count can be limited when the field is unfocused.
Working
RHFTagsInput works as follows:
- Users can type a keyword, press Enter or the delimiter key (default
","), and see it rendered as a chip, with the input field cleared for the next entry. - Pasting comma-separated values automatically generates chips for each value.
The delimiter can also be configured, for example
"|". - Users can remove a chip by clicking its "x" button.
- Pressing the Backspace or Delete key when the input is empty removes the last chip.
- When the field is unfocused, only the first two chips are displayed by
default. This can be customized via the
limitTagsprop, with-1showing all chips.
Usage
import RHFTagsInput, { RHFTagsInputProps } from '@nish1896/rhf-mui-components/mui/tags-input';import { useForm } from 'react-hook-form';
type FormValues = {
tags: string[];
};
const { control, handleSubmit } = useForm<FormValues>({
defaultValues: { tags: [] }
});
<form onSubmit={handleSubmit(values => console.log(values))}>
<RHFTagsInput
fieldName="tags"
control={control}
delimiter="|"
/>
</form>The stored value is always a string[], and a missing value is an empty list.
Removing the last tag stores [], never null. Tags are trimmed, empty entries
are dropped, and a tag is skipped when it matches an existing one, ignoring
letter case and spaces (React and react, or New York and newyork).
onValueChange receives { newValue }, the next array, after it has been
stored.
Delimiter
The delimiter (default ',') is the key that turns the typed text into a tag,
alongside Enter. Pasted text is split on it as well, so pasting
red;green;blue creates three tags when the delimiter is ';'. Leading and
trailing spaces around each tag are trimmed, so red; green ; blue creates the
same three tags.
<RHFTagsInput
fieldName="colors"
control={control}
delimiter=";"
/>The delimiter is matched against the pressed key, so use a single character. That key is intercepted, which means a tag can't contain the delimiter.
Tag Events
Use onTagAdd, onTagDelete, and onTagPaste to validate, transform, or
prevent tag changes before the form value is updated. Each callback receives a
single object argument with the current field value available as currentValue.
onTagAdd: called before a tag is added, withcurrentValue(the field value before the addition) andnewTag(the tag the user is attempting to add). Returnfalseto block the tag, a replacementstringto add a different value instead ofnewTag, ortrue/voidto addnewTagunchanged.onTagDelete: called before a tag is removed, withcurrentValue(the field value before the removal) anddeletedTag(the tag being removed). Returnfalseto prevent the deletion, ortrue/voidto allow it.onTagPaste: called when one or more tags are pasted, withcurrentValueandpastedTags(the tags parsed from the pasted text, already split on the configureddelimiter, trimmed, and deduplicated). Returnfalseto discard all pasted tags, astring[]to replace them with a custom set, orvoidto addpastedTagsunchanged.
<RHFTagsInput
fieldName="tags"
control={control}
onTagAdd={({ newTag, currentValue }) => {
if (newTag.length < 3 || currentValue.includes(newTag)) {
return false;
}
}}
onTagDelete={({ deletedTag }) => {
if (deletedTag.includes('sh')) {
return false;
}
}}
onTagPaste={({ pastedTags }) => (
pastedTags.filter(tag => tag.length >= 3)
)}
/>Limiting the visible tags
While the field is not focused, only the first limitTags tags (default 2)
are shown, followed by a "+N more" chip. Focusing the field shows every tag.
Set limitTags to -1 to always show all of them. getLimitTagsText receives
the number of hidden tags and returns the text of the extra chip:
<RHFTagsInput
fieldName="skills"
control={control}
limitTags={3}
getLimitTagsText={hiddenTags => `${hiddenTags} more…`}
/>Maximum number of tags
maxTags caps how many tags the field holds. By default there is no limit. Once
it is reached:
- New tags typed from the keyboard are ignored, and the text stays in the input.
- Pasted tags are cut to the free slots. Pasting five tags with two slots left adds the first two.
onTagAdd isn't called for a tag that is blocked by the limit. onTagPaste
still receives every parsed tag, and its result is cut to the free slots
afterwards. Read the current count with useWatch to show how many slots are
left:
const skills = useWatch({ control, name: 'skills' });
<RHFTagsInput
fieldName="skills"
control={control}
maxTags={5}
helperText={`${skills.length}/5 tags`}
/>Validation
Rules go in registerOptions. A required rule treats an empty list as
missing, and validate can check the contents:
<RHFTagsInput
fieldName="tags"
control={control}
registerOptions={{
validate: value =>
value.length >= 2 || 'Add at least two tags'
}}
/>Customizing the chips
ChipProps is forwarded to every tag
Chip, for example color, variant,
size or an icon. It also applies to the "+N more" chip. The id,
role, label, disabled and onDelete props are controlled by the
component:
<RHFTagsInput
fieldName="topics"
control={control}
ChipProps={{ color: 'primary', variant: 'outlined', size: 'small' }}
/>Transform tag content
By default, each chip shows its tag exactly as it was typed. To transform how a
tag is displayed, for example by adding a # prefix, changing its letter case
or adding an icon, pass a function to renderTagLabel. The stored value stays
the same; only the chip's label changes.
renderTagLabel receives a tag string and returns the ReactNode to display as
that chip's label. For example, to prefix every tag with #:
<RHFTagsInput
fieldName="topics"
control={control}
renderTagLabel={tag => `#${tag}`}
/>The label can be any element, such as an icon next to the text:
import LocalOfferIcon from '@mui/icons-material/LocalOffer';
<RHFTagsInput
fieldName="topics"
control={control}
renderTagLabel={tag => (
<>
<LocalOfferIcon
sx={{
fontSize: 14,
mr: 0.5,
verticalAlign: 'middle'
}}
/>
{tag}
</>
)}
/>This only transforms the content display in an individual chip. The stored
value, the onTagAdd, onTagDelete and onTagPaste callbacks, and the
duplicate check all keep using the original tag, so #react is shown but
'react' is stored. The "+N more" chip isn't affected; use
getLimitTagsText to change it.
Handling value changes
onValueChange runs after the new array has been stored in the form. It
receives { newValue }:
<RHFTagsInput
fieldName="tags"
control={control}
onValueChange={({ newValue }) => saveDraft(newValue)}
/>RHFTagsInput has no customOnChange. To change what gets stored, intercept
tags before they are added with onTagAdd and onTagPaste, and before they are
removed with onTagDelete (see Tag Events). This example stores
every tag in lowercase:
<RHFTagsInput
fieldName="tags"
control={control}
onTagAdd={({ currentValue, newTag }) => newTag.toLowerCase()}
onTagPaste={({ currentValue, pastedTags }) => (
pastedTags.map(tag => tag.toLowerCase())
)}
/>Examples
API
The RHFTagsInputProps 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. |
onValueChange | ({ newValue }) => void | An optional callback function that returns all tags present in the input. |
onTagAdd | ({ currentValue, newTag }) => boolean / string / void | Callback function triggered before a tag is added by pressing Enter or the configured delimiter key. Receives the tag being added and the current field value. Return false to prevent the tag from being added. Return a string to replace the original tag value before it is added. |
onTagDelete | ({ currentValue, deletedTag }) => boolean / void | Callback function triggered before a tag is removed. Receives the tag being deleted and the current field value. Return false to prevent the tag from being deleted. |
onTagPaste | ({ currentValue, pastedTags }) => boolean / string[] / void | Callback function triggered when tags are pasted into the input. The pasted text is split using the configured delimiter, trimmed, and deduplicated before this callback is invoked. Receives the parsed tags and the current field value. Return false to prevent all pasted tags from being added, or return a string array to replace the parsed tags. |
delimiter | string | Character used to separate tags when typing or pasting. Pressing the delimiter key commits the current input as one or more tags, and pasted values are split using the same delimiter. |
maxTags | number | Maximum number of tags that can be added. Once the limit is reached, additional tags entered from the keyboard are ignored, and pasted tags are truncated to the remaining available slots. |
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. |
ChipProps | ChipProps | Props to customise the Chip component for each input tag. |
limitTags | number | Maximum number of tags to show when the input is not focused. Provide value as -1 to show all tags.Default value is 2. |
getLimitTagsText | (hiddenTags: number) => ReactNode | Custom renderer for the summary label displayed when tags are hidden. |
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.

