Demos
How to import
import { TagInput } from '@fibrous/semi-ui-react';
Basic Usage
After pressing the Enter key, the input will add value as a tag. If the tag content is an empty string or pure space, it will be filtered.
抖音
火山
西瓜视频
Code
import { TagInput } from '@fibrous/semi-ui-react';
export default function TagInputDemo() {
return <TagInput defaultValue={['抖音', '火山', '西瓜视频']} placeholder="请输入..." onChange={(v) => console.log(v)} />;
}Batch Add
You can use separator to set the separator to achieve batch input, and its default value is a comma. Multiple separators are supported in string[] format.
Code
import { TagInput } from '@fibrous/semi-ui-react';
export default function TagInputDemo() {
return (
<>
<TagInput separator="-" placeholder="使用 - 进行批量输入" onChange={(v) => console.log(v)} />
<br />
<br />
<TagInput separator={['-', '/', '|', '++']} placeholder="支持多个分隔符进行批量输入" onChange={(v) => console.log(v)} />
</>
);
}Batch Remove
You can also use showClear to set whether to support one-click deletion of all tags and input.
抖音
火山
Code
import { TagInput } from '@fibrous/semi-ui-react';
export default function TagInputDemo() {
return <TagInput showClear defaultValue={['抖音', '火山']} placeholder="请输入..." onChange={(v) => console.log(v)} />;
}Disabled
抖音
火山
西瓜视频
Code
import { TagInput } from '@fibrous/semi-ui-react';
export default function TagInputDemo() {
return <TagInput disabled showClear defaultValue={['抖音', '火山', '西瓜视频']} placeholder="请输入..." />;
}Size
Use size to set the size of the TagInput, optional: small, default, large.
Code
import { TagInput } from '@fibrous/semi-ui-react';
export default function TagInputDemo() {
return (
<>
<TagInput size="small" placeholder="small" />
<br />
<br />
<TagInput placeholder="default" />
<br />
<br />
<TagInput size="large" placeholder="large" />
</>
);
}Different validate status
validateStatus: default, warning, error.
Code
import { TagInput } from '@fibrous/semi-ui-react';
export default function TagInputDemo() {
return (
<>
<TagInput placeholder="default" />
<br />
<br />
<TagInput placeholder="warning" validateStatus="warning" />
<br />
<br />
<TagInput placeholder="error" validateStatus="error" />
</>
);
}Prefix / Suffix
You can pass the input box prefix through prefix, the input box suffix through suffix, for text or React Node.
The left and right padding is automatically brought when the content passed in by prefix and suffix is text or Icon. If it is a custom ReactNode, the left and right padding is 0. If necessary, you can set it in the ReactNode you passed in.
Code
import { IconVigoLogo, IconGift } from '@fibrous/semi-icons-react';
import { TagInput } from '@fibrous/semi-ui-react';
export default function TagInputDemo() {
return (
<>
<TagInput prefix={<IconVigoLogo />} />
<br />
<br />
<TagInput prefix="Prefix" />
<br />
<br />
<TagInput suffix={<IconGift />} />
<br />
<br />
<TagInput suffix="Suffix" />
</>
);
}Autocomplete
You can use addOnBlur to set whether the current input value is automatically created as a tag when the blur event is triggered.
抖音
火山
西瓜视频
Code
import { TagInput } from '@fibrous/semi-ui-react';
export default function TagInputDemo() {
return <TagInput defaultValue={['抖音', '火山', '西瓜视频']} addOnBlur placeholder="请输入..." onChange={(v) => console.log(v)} />;
}Allow Duplicates
You can use allowDuplicates to set whether to allow the creation of the same tag.
抖音
火山
西瓜视频
Code
import { TagInput } from '@fibrous/semi-ui-react';
export default function TagInputDemo() {
return <TagInput defaultValue={['抖音', '火山', '西瓜视频']} allowDuplicates={false} placeholder="请输入..." onChange={(v) => console.log(v)} />;
}Limits
You can use max to limit the number of tags. Tags added past the limit are dropped, and the onExceed() callback is invoked.
You can use maxLength to limit the maximum length of a single tag, and the onInputExceed() callback will be invoked when this value is exceeded.
Code
import { TagInput, Toast } from '@fibrous/semi-ui-react';
export default function TagInputDemo() {
return (
<>
<TagInput
max={3}
placeholder="最多输入3条标签.."
onChange={(v) => console.log(v)}
onExceed={(v) => {
Toast.warning('超过 max');
console.log(v);
}}
/>
<TagInput
maxLength={5}
placeholder="单个标签长度不超过5..."
style={{ marginTop: 12 }}
onChange={(v) => console.log(v)}
onInputExceed={(v) => {
Toast.warning('超过 maxLength');
console.log(v);
}}
/>
</>
);
}Limit the number of tags displayed
You can use maxTagCount to limit the number of tags displayed, and the excess will be displayed as +N. You can use showRestTagsPopover to set whether hover +N displays Popover after maxTagCount is exceeded, and you can configure Popover in the restTagsPopoverProps property.
抖音
火山
Code
import { TagInput } from '@fibrous/semi-ui-react';
export default function TagInputDemo() {
return <TagInput maxTagCount={2} showRestTagsPopover restTagsPopoverProps={{ position: 'top' }} defaultValue={['抖音', '火山', '西瓜视频']} onChange={(v) => console.log(v)} />;
}Controlled Tag
You can use value to set tags, and use onChange to achieve control of the tags.
抖音
Code
import { useState } from 'react';
import { TagInput } from '@fibrous/semi-ui-react';
export default function TagInputDemo() {
const [value, setValue] = useState(['抖音']);
const handleChange = (v: string[]) => setValue(v);
return <TagInput value={value} onChange={handleChange} />;
}Controlled Input
You can use inputValue to set input box, and use onInputChange to control the input content.
Code
import { useState } from 'react';
import { TagInput } from '@fibrous/semi-ui-react';
export default function TagInputDemo() {
const [value, setValue] = useState('abc');
const handleInputChange = (v: string) => setValue(v);
return <TagInput inputValue={value} onInputChange={handleInputChange} />;
}Callback
抖音
Code
import { TagInput } from '@fibrous/semi-ui-react';
export default function TagInputDemo() {
return (
<TagInput
defaultValue={['抖音']}
placeholder="请输入..."
showClear
onFocus={() => {
console.log(`onFocus`);
}}
onBlur={() => {
console.log(`onBlur`);
}}
onChange={(tag) => {
console.log(`onChange,当前标签数组:${tag}`);
}}
onAdd={(tag) => {
console.log(`onAdd,新增:${tag}`);
}}
onRemove={(v, i) => {
console.log(`onRemove,移除:${v}, 序号:${i}`);
}}
onInputChange={(input) => {
console.log(`onInputChange,当前输入内容:${input}`);
}}
/>
);
}Focus Management
You can use the blur() and focus() methods to manage the focus.
抖音
火山
Code
import { useRef } from 'react';
import { TagInput, Button, type TagInputHandle } from '@fibrous/semi-ui-react';
export default function TagInputDemo() {
const ref = useRef<TagInputHandle>(null);
const handleTagInputFocus = () => {
ref.current?.focus();
};
return (
<>
<TagInput defaultValue={['抖音', '火山']} ref={ref} />
<Button style={{ marginTop: 10 }} onClick={handleTagInputFocus}>
点击按钮聚焦
</Button>
</>
);
}Custom TagInput rendering
You can use renderTagItem to customize tag rendering. renderTagItem(value: string, index: number, onClose: function ) => React.ReactNode The component adds a key to each item.
Code
import { useMemo, useState } from 'react';
import { IconClose } from '@fibrous/semi-icons-react';
import { TagInput, Avatar, Button } from '@fibrous/semi-ui-react';
export default function TagInputDemo() {
const [value, setValue] = useState(['夏可漫']);
const list = useMemo(
() => [
{
name: '夏可漫',
avatar: '/assets/root-web-sites/avatarDemo.jpeg',
},
{
name: '申悦',
avatar: '/assets/root-web-sites/bf8647bffab13c38772c9ff94bf91a9d.jpg',
},
{
name: '曲晨一',
avatar: '/assets/root-web-sites/bf8647bffab13c38772c9ff94bf91a9d.jpg',
},
{
name: '文嘉茂',
avatar: '/assets/root-web-sites/avatarDemo.jpeg',
},
],
[]
);
const mapList = useMemo(() => new Map(list.map((item) => [item.name, item])), [list]);
const renderTagItem = (value: string, index: number, onClose: () => void) => {
const data = mapList.get(value);
return (
<div
key={index}
style={{
backgroundColor: 'var(--semi-color-info-light-default)',
padding: '4px 8px',
borderRadius: 12,
display: 'flex',
alignItems: 'center',
fontSize: 14,
marginRight: 10,
}}
>
<Avatar alt="avatar" src={data ? data.avatar : '/assets/placeholder/avatar-a.svg'} size="extra-small" />
<span style={{ marginLeft: 8 }}>{`${value}@semi.com`}</span>
<Button theme="borderless" type="tertiary" size="small" icon={<IconClose size="small" />} aria-label={`移除 ${value}`} onClick={onClose} />
</div>
);
};
return <TagInput value={value} onChange={setValue} renderTagItem={renderTagItem} />;
}Drag to sort
Set draggable to true to enable drag and drop sorting. After the drag function is enabled, once TagInput is focused (by click or Tab) the tags can be dragged; after the focus leaves TagInput they cannot. The drag handle sits beside its tag and works from the keyboard, see "Keyboard and focus" below. Tags with the same value can be sorted separately.
抖音
火山
西瓜视频
Code
import { TagInput } from '@fibrous/semi-ui-react';
export default function TagInputDemo() {
return <TagInput draggable allowDuplicates={false} defaultValue={['抖音', '火山', '西瓜视频']} placeholder="请输入..." onChange={(v) => console.log(v)} />;
}API Reference
Props
| Property | Description | Type | Default |
|---|---|---|---|
| addOnBlur | Whether the input text becomes a tag when the focus leaves the whole component. | boolean | false |
| allowDuplicates | Whether the same tag can be added more than once. | boolean | true |
| aria-label | Accessible name of the input. It is set on the input, not on the root. | string | - |
| autoFocus | Whether the input is focused and the component activated on mount; ignored when disabled. | boolean | false |
| className | Class name of the root element. | string | - |
| clearIcon | Replaces the icon in the clear button; the default icon is used when omitted. | React.ReactNode | - |
| defaultValue | Initial tags when uncontrolled. | string[] | - |
| disabled | Whether the component is disabled. The input becomes native disabled and the tags become static text. | boolean | - |
| draggable | Whether tags can be reordered by dragging. | boolean | false |
| expandRestTagsOnClick | Whether the tags folded by maxTagCount expand once focus enters the component (click, Tab or focus()); when false, they stay folded. | boolean | true |
| inputValue | Current input text. Pair it with onInputChange for a controlled input. | string | - |
| insetLabel | Inset label shown before the input; it is hidden when prefix is also given. When shown, it names an input that has no aria-label or aria-labelledby. | React.ReactNode | - |
| insetLabelId | id of the inset label container, for aria-labelledby; the component generates one when the inset label is shown and this is omitted. | string | - |
| max | Maximum number of tags. The part beyond it does not become tags, and onExceed is called. | number | - |
| maxLength | Maximum length of one tag. Input beyond it is rejected, and onInputExceed is called. | number | - |
| maxTagCount | Maximum number of tags shown; the rest are folded into +N. They expand while the component is active, unless expandRestTagsOnClick is false. | number | - |
| onAdd | Called when tags are added, with the tags actually added; those beyond max are excluded. | Type(addedValue: string[]) => void | - |
| onBlur | Called once when the focus leaves the whole component; moving focus inside it does not call it. | Type(e: React.FocusEvent<HTMLDivElement>) => void | - |
| onChange | Called when the tags change, with the whole list of tags. | Type(value: string[]) => void | - |
| onExceed | Called when adding would exceed max, with the whole list before it is cut. | Type(value: string[]) => void | - |
| onFocus | Called once when the focus enters from outside; moving between the input, tags and clear button does not call it. | Type(e: React.FocusEvent<HTMLDivElement>) => void | - |
| onInputChange | Called when the input text changes, with the new text and the event that caused it. The event may be an input event, a KeyboardEvent (Enter adds), a FocusEvent (addOnBlur), a MouseEvent (clear) or a CompositionEvent (IME truncation); narrow it by event.type before reading its own fields. | Type(value: string, e: React.SyntheticEvent) => void | - |
| onInputExceed | Called when the input text exceeds maxLength, with the rejected input text. | Type(value: string) => void | - |
| onKeyDown | Called on keydown in the input after the component has handled it; calling preventDefault there does not stop Enter from adding a tag. | Type(e: React.KeyboardEvent<HTMLInputElement>) => void | - |
| onRemove | Called when a tag is removed, with the removed tag and its index. | Type(removedValue: string, idx: number) => void | - |
| placeholder | Placeholder of the input while there are no tags. | string | - |
| prefix | Prefix of the input; text or an icon gets side spacing automatically, while a custom node gets none and can set its own. | React.ReactNode | - |
| preventScroll | Whether the focus() calls inside the component stop the browser from scrolling the focused element into view. | boolean | - |
| ref | Handle exposing the focus() and blur() methods; it is not the root element. | TypeReact.Ref<TagInputHandle> | - |
| renderTagItem | Renders each tag with a custom node in place of the default tag; the component adds a key to each item. The third argument, onClose, removes that tag and can be passed directly as a button's onClick. | Type(value: string, index: number, onClose: () => void) => React.ReactNode | - |
| restTagsPopoverProps | Popover props of the +N overlay, such as position and trigger, which default to top and hover, see Popover API Reference; do not pass content, it replaces the list of remaining tags. | RestTagsPopoverProps | - |
| separator | Separator(s) for adding several tags at once; null disables splitting. | string | string[] | null | "," |
| showClear | Whether to show the button that clears all tags and the input text. | boolean | false |
| showContentTooltip | Whether hovering a truncated tag shows its full text in an overlay; an object sets the overlay type (tooltip or popover) and passes opts to it. | boolean | ShowTooltip | true |
| showRestTagsPopover | Whether hovering +N shows the remaining tags in a Popover once maxTagCount is exceeded. | boolean | true |
| size | Size: small, default or large. | Size | "default" |
| split | Custom split function that receives the raw string and separator, and returns the split strings. | Type(originString: string, separators: string | string[] | null) => string[] | - |
| style | Style of the root element. | React.CSSProperties | - |
| suffix | Suffix of the input; text or an icon gets side spacing automatically, while a custom node gets none and can set its own. | React.ReactNode | - |
| validateStatus | Validation status, which only affects styling; error also sets aria-invalid on the input. | ValidateStatus | "default" |
| value | Current tags, pair it with onChange for a controlled list; undefined means uncontrolled, null means controlled with no tags. | string[] | null | - |
Methods
| Method | Description | Type |
|---|---|---|
| blur | Removes focus from the focused element inside the component and deactivates it. | Type() => void |
| focus | Focuses the input and activates the component; the component is not activated when disabled. | Type() => void |
Among the native attributes, id, name, role, tabIndex and the aria-* attributes that describe the input (aria-label, aria-labelledby, aria-describedby, aria-invalid, aria-required, aria-controls, aria-expanded, aria-haspopup, aria-autocomplete, aria-activedescendant, aria-errormessage) land on the inner input; the rest, such as data-*, title, onClick and onMouseDown, land on the root element, where your onClick and the component's own activation handler both run.
Accessibility
ARIA
- TagInput supports the input of
aria-labelto indicate the function of the TagInput; it lands on the input box, not on the root node; - The root node has the
grouprole, which holds the input, the tags and the clear button as one control; when disabled it carriesaria-disabled="true", otherwise it has noaria-disabled; - When disabled, the input is natively
disabledand the tags are static text without anaria-label; withvalidateStatusset toerrorthe input carriesaria-invalid, and an explicitaria-invalidwins; - With
showClear, tags or input text, and nodisabled, a clear button is rendered. It is a nativebuttonnamed "Clear TagInput value" from the locale, shown on hover or while focus is inside the TagInput. From the input,Tabmoves to the clear button;EnterorSpaceclears, as a mouse click does, and the focus goes back to the input.Backspacein the empty input also removes the last tag.
Keyboard and focus
Enterin the input adds the input text as a tag; with empty input it does nothing.Enteralways has its default action prevented, so a TagInput inside a form never submits it.Backspacein the empty input removes the last tag.- A closable tag is a
role="button"Tab stop placed before the input; with a tag focused,BackspaceorDeletecloses it and the focus goes back to the input. When disabled, tags are static text and not focusable. - With
showClearand some content, the clear button follows the input:Tabreaches it,EnterorSpaceclears, and the focus goes back to the input. - The active state follows the focus: it starts when the focus comes in from outside (click,
Taborfocus()) and ends when it leaves the whole component. Moving the focus between the input, the tags and the clear button is not leaving, so it does not firefocusorblurand does not triggeraddOnBlur. While active, tags folded bymaxTagCountexpand (unlessexpandRestTagsOnClickisfalse). - With
draggableand the component active, each tag gets a drag handle that is its own Tab stop, placed before the tag it belongs to. Focus a handle, pressSpaceto pick up, the arrow keys to move andSpaceto drop; screen readers announce the pick up, moves and drop.
Design Tokens
| Sass variable | Value | Usage |
|---|---|---|
| $transition_duration-tagInput-bg | var(--semi-transition_duration-none) | 标签输入框-背景色-动画持续时间 |
| $transition_function-tagInput-bg | var(--semi-transition_function-easeIn) | 标签输入框-背景色-过渡曲线 |
| $transition_delay-tagInput-bg | var(--semi-transition_delay-none) | 标签输入框-背景色-延迟时间 |
| $transition_duration-tagInput-border | var(--semi-transition_duration-none) | 标签输入框-边框-动画持续时间 |
| $transition_function-tagInput-border | var(--semi-transition_function-easeIn) | 标签输入框-边框-过渡曲线 |
| $transition_delay-tagInput-border | var(--semi-transition_delay-none) | 标签输入框-边框-延迟时间 |
| $color-tagInput-icon-default | var(--semi-color-text-2) | 标签输入框图标颜色 - 默认 |
| $color-tagInput-icon-hover | var(--semi-color-primary-hover) | 标签输入框图标颜色 - 悬浮 |
| $color-tagInput_disabled-text-default | var(--semi-color-disabled-text) | 标签输入框禁用文字颜色 |
| $color-tagInput_disabled-bg | var(--semi-color-disabled-fill) | 标签输入框禁用背景色 |
| $color-tagInput_default-bg-focus | var(--semi-color-fill-0) | 标签输入框背景颜色 - 选中态 |
| $color-tagInput-border-default | transparent | 标签输入框描边颜色 - 默认 |
| $color-tagInput-border-hover | transparent | 标签输入框描边颜色 - 悬浮 |
| $color-tagInput-border-focus | var(--semi-color-focus-border) | 标签输入框描边颜色 - 选中态 |
| $color-tagInput_prefix-default | var(--semi-color-text-2) | 标签输入框 prefix 颜色 |
| $color-tagInput_suffix-default | var(--semi-color-text-2) | 标签输入框 suffix 颜色 |
| $color-tagInput_default-bg-default | var(--semi-color-fill-0) | 标签输入框背景颜色 - 默认 |
| $color-tagInput_default-bg-hover | var(--semi-color-fill-1) | 标签输入框背景颜色 - 悬浮 |
| $color-tagInput_warning-bg-default | var(--semi-color-warning-light-default) | 警告标签输入框背景颜色 - 默认 |
| $color-tagInput_warning-border-default | var(--semi-color-warning-light-default) | 警告标签输入框描边颜色 - 默认 |
| $color-tagInput_warning-bg-hover | var(--semi-color-warning-light-hover) | 警告标签输入框背景颜色 - 悬浮 |
| $color-tagInput_warning-border-hover | var(--semi-color-warning-light-hover) | 警告标签输入框描边颜色 - 悬浮 |
| $color-tagInput_warning-bg-focus | var(--semi-color-warning-light-default) | 警告标签输入框背景颜色 - 选中 |
| $color-tagInput_warning-border-focus | var(--semi-color-warning) | 警告标签输入框描边颜色 - 选中 |
| $color-tagInput_danger-bg-default | var(--semi-color-danger-light-default) | 危险标签输入框背景颜色 - 默认 |
| $color-tagInput_danger-border-default | var(--semi-color-danger-light-default) | 危险标签输入框描边颜色 - 默认 |
| $color-tagInput_danger-bg-hover | var(--semi-color-danger-light-hover) | 危险标签输入框背景颜色 - 悬浮 |
| $color-tagInput_danger-border-hover | var(--semi-color-danger-light-hover) | 危险标签输入框描边颜色 - 悬浮 |
| $color-tagInput_danger-bg-focus | var(--semi-color-danger-light-default) | 危险标签输入框背景颜色 - 选中 |
| $color-tagInput_danger-border-focus | var(--semi-color-danger) | 危险标签输入框描边颜色 - 选中 |
| $color-tagInput_sortable_item_over-bg | var(--semi-color-primary) | 拖拽经过的元素前竖线背景色 |
| $color-tagInput_handler-icon-default | var(--semi-color-text-2) | 可拖拽的标签拖拽按钮颜色 |
| $spacing-tagInput_small-Y | 1px | 小尺寸标签输入框标签顶部外边距 |
| $spacing-tagInput_default-Y | $spacing-super-tight | 默认尺寸标签输入框标签顶部外边距 |
| $spacing-tagInput_large-Y | 3px | 大尺寸标签输入框标签顶部外边距 |
| $spacing-tagInput_wrapper_n_paddingX | $spacing-tight | 标签输入框标签容器水平内边距 |
| $spacing-tagInput_drag_handler-marginRight | 4px | 拖拽handler icon的右外边距 |
| $spacing-tagInput_tag_icon_paddingLeft | 4px | tag中有handler icon时tag的左内边距 |
| $spacing-tagInput_prefix_suffix-marginX | $spacing-base-tight | 标签输入框 prefix/suffix 水平外边距 |
| $height-tagInput-large | $height-control-large | 大尺寸标签输入框高度 |
| $height-tagInput-default | $height-control-default | 默认尺寸标签输入框高度 |
| $height-tagInput-small | $height-control-small | 小尺寸标签输入框高度 |
| $height-tagInput_input_small | 20px | 小尺寸标签输入框Input框高度 |
| $height-tagInput_input_default | 24px | 默认尺寸标签输入框Input框高度 |
| $height-tagInput_input_large | 24px | 大尺寸标签输入框Input框高度 |
| $width-tagInput-clear-medium | $width-icon-medium * 2 | 标签输入框清空按钮宽度 |
| $width-tagInput-border-default | $border-thickness-control | 标签输入框描边描边宽度 - 默认 |
| $width-tagInput-border-hover | $width-tagInput-border-default | 标签输入框描边描边宽度 - 悬浮 |
| $width-tagInput-border-focus | $border-thickness-control-focus | 标签输入框描边宽度 - 选中态 |
| $width-tagInput_sortable_item_over | 2px | 拖拽经过的元素前竖线宽度 |
| $radius-tagInput | var(--semi-border-radius-small) | 标签输入框圆角 |
| $font-tagInput_prefix_suffix-fontWeight | $font-weight-bold | 标签输入框 prefix/suffix 文字字重 |