react-tag-autocomplete vs react-tag-input vs taggle
タグ入力ライブラリ
react-tag-autocompletereact-tag-inputtaggle類似パッケージ:
タグ入力ライブラリ

タグ入力ライブラリは、ユーザーが入力フィールドにタグを追加、削除、編集できるようにするためのコンポーネントです。これらのライブラリは、ユーザーが複数の選択肢を簡単に管理できるようにし、特にフォームや検索機能でのユーザーエクスペリエンスを向上させます。

npmのダウンロードトレンド
3 年
GitHub Starsランキング
統計詳細
パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
react-tag-autocomplete56,208201402 kB74ヶ月前ISC
react-tag-input37,5531,553310 kB10610ヶ月前MIT
taggle2,828663119 kB6-MIT
機能比較: react-tag-autocomplete vs react-tag-input vs taggle

オートコンプリート機能

  • react-tag-autocomplete:

    react-tag-autocompleteは、ユーザーがタグを入力する際に、リアルタイムで候補を表示するオートコンプリート機能を提供します。これにより、ユーザーは既存のタグを簡単に選択でき、入力の手間を減らします。

  • react-tag-input:

    react-tag-inputにはオートコンプリート機能は組み込まれていませんが、カスタム実装が可能です。ユーザーが自由にタグを入力できるため、柔軟性があります。

  • taggle:

    taggleは、オートコンプリート機能を提供していませんが、シンプルなタグ入力を実現します。ユーザーは手動でタグを追加する必要がありますが、その分シンプルさが保たれています。

カスタマイズ性

  • react-tag-autocomplete:

    react-tag-autocompleteは、スタイルや動作を簡単にカスタマイズできる柔軟性があります。特定のニーズに合わせてコンポーネントを調整できるため、デザインの一貫性を保つことができます。

  • react-tag-input:

    react-tag-inputは、タグの表示方法やスタイルを自由にカスタマイズできるため、開発者が独自のデザインを実現しやすいです。

  • taggle:

    taggleは、基本的なスタイルを提供しますが、カスタマイズの自由度は低いです。シンプルさを重視する場合には適していますが、独自のデザインを求める場合には制約があります。

学習曲線

  • react-tag-autocomplete:

    react-tag-autocompleteは、オートコンプリート機能を持つため、若干の学習が必要ですが、ドキュメントが充実しているため、比較的短期間で習得可能です。

  • react-tag-input:

    react-tag-inputは、シンプルなAPIを提供しているため、学習曲線は緩やかです。特に、Reactに慣れている開発者にとっては、すぐに使い始めることができます。

  • taggle:

    taggleは、非常にシンプルで直感的なインターフェースを持っているため、学習曲線はほとんどありません。すぐに使い始めることができます。

パフォーマンス

  • react-tag-autocomplete:

    react-tag-autocompleteは、オートコンプリート機能を持つため、入力時にリアルタイムで候補を表示する際に、パフォーマンスが重要です。適切に最適化されているため、大量のデータでもスムーズに動作します。

  • react-tag-input:

    react-tag-inputは、シンプルなタグ管理を提供するため、パフォーマンスは良好です。タグの追加や削除が迅速に行えます。

  • taggle:

    taggleは、軽量なライブラリであるため、パフォーマンスに優れています。特に、少数のタグを扱う場合において、非常にスムーズに動作します。

メンテナンス

  • react-tag-autocomplete:

    react-tag-autocompleteは、活発にメンテナンスされており、定期的にアップデートが行われています。バグ修正や新機能の追加が期待できます。

  • react-tag-input:

    react-tag-inputも定期的にメンテナンスされており、コミュニティのサポートが充実しています。問題が発生した場合でも、解決策を見つけやすいです。

  • taggle:

    taggleは、比較的シンプルなライブラリであるため、メンテナンスは容易ですが、更新頻度は他のライブラリに比べて低いかもしれません。

選び方: react-tag-autocomplete vs react-tag-input vs taggle
  • react-tag-autocomplete:

    react-tag-autocompleteは、オートコンプリート機能を必要とする場合に最適です。ユーザーが入力を開始すると、候補が表示され、選択できるため、タグの選択がスムーズになります。

  • react-tag-input:

    react-tag-inputは、シンプルでカスタマイズ可能なタグ入力が必要な場合に適しています。特に、タグの追加や削除が簡単で、ユーザーインターフェースを柔軟に設計したい場合に便利です。

  • taggle:

    taggleは、軽量でシンプルなタグ入力を提供します。特に、複雑な機能が不要で、基本的なタグ管理機能を求める場合に適しています。

react-tag-autocomplete のREADME

React Tag Autocomplete

GitHub license build status Coverage Status npm version

React Tag Autocomplete is a simple, accessible, tagging component ready to drop into your React projects. Try the examples here.

Screenshot showing React Tag Autocomplete used as a country selector

Please note: This repository is for v7 and above. To view the previous versions of this package, compatible with React v16 and v17, go to the old repository. If you're upgrading from v6 please see to the migration guide

Installation

This is a Node.js module available through the npm registry. Node 16 and React 18 or above are required.

Installation is done using the npm install command:

$ npm install -S react-tag-autocomplete

Usage

import React, { useCallback, useState } from 'react'
import { ReactTags } from 'react-tag-autocomplete'
import { suggestions } from './country-list'

function CountrySelector() {
  const [selected, setSelected] = useState([])

  const onAdd = useCallback(
    (newTag) => {
      setSelected([...selected, newTag])
    },
    [selected]
  )

  const onDelete = useCallback(
    (tagIndex) => {
      setSelected(selected.filter((_, i) => i !== tagIndex))
    },
    [selected]
  )

  return (
    <ReactTags
      labelText="Select countries"
      selected={selected}
      suggestions={suggestions}
      onAdd={onAdd}
      onDelete={onDelete}
      noOptionsText="No matching countries"
    />
  )
}

Props

activateFirstOption (optional)

Automatically activate the first option when the listbox expands and switch the active option directly from first to last/last to first when the selection wraps. Defaults to false.

allowBackspace (optional)

Enable users to delete selected tags when the backspace key is pressed whilst the text input is empty. Defaults to true.

allowNew (optional)

Enable users to add new (not suggested) tags based on the input text. The new tag label and value will be set as the input text. Defaults to false.

allowResize (optional)

Enable the text input to automatically resize to fit its value. Defaults to true.

ariaAddedText (optional)

The status text announced when a selected tag is added. The placeholder %value% will be replaced by the selected tag label. Defaults to "Added tag %value%".

ariaDeletedText (optional)

The status text announced when a selected tag is removed. The placeholder %value% will be replaced by the removed tag label. Defaults to "Removed tag %value%".

ariaDescribedBy (optional)

References elements by ID which contain more information about the component. Defaults to "".

ariaErrorMessage (optional)

References an element by ID which contains more information about errors relating to the component. Defaults to "".

classNames (optional)

Override the default class names used by the component. Defaults to:

{
  root: 'react-tags',
  rootIsActive: 'is-active',
  rootIsDisabled: 'is-disabled',
  rootIsInvalid: 'is-invalid',
  label: 'react-tags__label',
  tagList: 'react-tags__list',
  tagListItem: 'react-tags__list-item',
  tag: 'react-tags__tag',
  tagName: 'react-tags__tag-name',
  comboBox: 'react-tags__combobox',
  input: 'react-tags__combobox-input',
  listBox: 'react-tags__listbox',
  option: 'react-tags__listbox-option',
  optionIsActive: 'is-active',
  highlight: 'react-tags__listbox-option-highlight',
}

collapseOnSelect (optional)

Controls whether the listbox should automatically collapse when a tag is selected. Defaults to false.

deleteButtonText (optional)

The helper text added to each selected tag. The placeholder %value% will be replaced by the selected tag label. Defaults to "Remove %value% from the list".

delimiterKeys (optional)

Array of key names matching KeyboardEvent key values. When a matching key is pressed it will trigger tag selection. Defaults to ['Enter'].

id (optional)

The ID attribute given to the component and used as a prefix for all sub-component IDs. This must be unique for each instance of the component. Defaults to: "ReactTags".

isDisabled (optional)

Disables all interactive elements of the component. Defaults to: false.

isInvalid (optional)

Marks the input as invalid. When true this should be used along with the ariaErrorMessage prop to provide details about the problem. Defaults to: false.

labelText (optional)

The label text used to describe the component and input. Please note that the label is visually hidden with CSS in the example code. Defaults to: "Select tags".

newOptionPosition (optional)

The position of the new tag option shown when the allowNew prop is enabled, either "first" or "last". Defaults to "last".

newOptionText (optional)

The text displayed in the new tag option shown when the allowNew prop is enabled. The placeholder %value% will be replaced by the current input value. Defaults to "Add %value%".

noOptionsText (optional)

The option text shown when there are no matching suggestions. The placeholder %value% will be replaced by the current input value. Defaults to "No options found for %value%".

onAdd (required)

Callback function called when the user wants to select a tag. Receives the tag. Example:

const [selected, setSelected] = useState([])

function onAdd(newTag) {
  setSelected([...selected, newTag])
}

onBlur (optional)

Callback function called when the component loses focus. Receives no arguments.

onCollapse (optional)

Callback function called when the listbox collapses. Receives no arguments.

onDelete (required)

Callback function called when the user wants to remove a selected tag. Receives the index of the selected tag. Example:

const [selected, setSelected] = useState([])

function onDelete(tagIndex) {
  setSelected(selected.filter((_, i) => i !== tagIndex))
}

onExpand (optional)

Callback function called when the listbox expands. Receives no arguments.

onFocus (optional)

Callback function called when the component gains focus. Receives no arguments.

onInput (optional)

Optional callback function called each time the input value changes. Receives the new input value. Example:

const [value, setValue] = useState('')

function onInput(value) {
  setValue(value)
}

onShouldCollapse (optional)

Optional callback function called before the listbox collapses and can be used to override the behavior and force the listbox to remain expanded. Receives the input value and should return a boolean. Example:

function onShouldCollapse(value) {
  return value.length === 0
}

onShouldExpand (optional)

Optional callback function called before the listbox expands and can be used to override the behavior and force the listbox to remain collapsed. Receives the input value and should return a boolean. Example:

function onShouldExpand(value) {
  return value.length > 1
}

onValidate (optional)

Callback function called when the input value changes and is used to enable or disable the new option when the allowNew prop is true. Receives the new input value and should return a boolean. Example:

function onValidate(value) {
  return /^[a-z]{4,12}$/i.test(value)
}

placeholderText (optional)

The placeholder text shown in the input when it is empty. Defaults to "Add a tag".

renderHighlight (optional)

A custom option text highlight component to render. Receives the highlighted text and classNames as props. Defaults to null.

function CustomHighlight({ classNames, text }) {
  return <span className={classNames.highlight}>{text}</span>
}

renderInput (optional)

A custom text input component to render. Receives required input element attributes, input width (if allowResize prop is enabled) and classNames as props. Defaults to null.

function CustomInput({ classNames, inputWidth, ...inputProps }) {
  return <input className={classNames.input} style={{ width: inputWidth }} {...inputProps} />
}

renderLabel (optional)

A custom label component to render. Receives the label text as children, required label element attributes, and classNames as props. Defaults to null.

function CustomLabel({ children, classNames, ...labelProps }) {
  return (
    <div className={classNames.label} {...labelProps}>
      {children}
    </div>
  )
}

renderListBox (optional)

A custom list box component to render. Receives the options as children, required list box element attributes, and classNames as props. Defaults to null.

function CustomListBox({ children, classNames, ...listBoxProps }) {
  return (
    <div className={classNames.listBox} {...listBoxProps}>
      {children}
    </div>
  )
}

renderOption (optional)

A custom option component to render. Receives the pre-rendered text as children, option object, required option element attributes, and classNames as props. Defaults to null.

function CustomOption({ children, classNames, option, ...optionProps }) {
  const classes = [
    classNames.option,
    option.active ? 'is-active' : '',
    option.selected ? 'is-selected' : '',
  ]

  return (
    <div className={classes.join(' ')} {...optionProps}>
      {children}
    </div>
  )
}

renderRoot (optional)

A custom root component to render. Receives the selected tag list and combobox as children, component states, required root element attributes, and classNames as props. Defaults to null.

function CustomRoot({ children, classNames, isActive, isDisabled, isInvalid, ...rootProps }) {
  const classes = [classNames.root]

  if (isActive) classes.push(classNames.rootIsActive)
  if (isDisabled) classes.push(classNames.rootIsDisabled)
  if (isInvalid) classes.push(classNames.rootIsInvalid)

  return (
    <div className={classes.join(' ')} {...rootProps}>
      {children}
    </div>
  )
}

renderTagList (optional)

A custom selected tag list component to render. Receives the selected tags as children, required tag list element attributes, and classNames as props. Defaults to null.

function CustomTagList({ children, classNames, ...tagListprops }) {
  return (
    <ul className={classNames.tagList} {...tagListprops}>
      {React.Children.map(children, (child) => (
        <li className={classNames.tagListItem} key={child.key}>
          {child}
        </li>
      ))}
    </ul>
  )
}

renderTag (optional)

A custom selected tag component to render. Receives the selected tag object, required tag element attributes, and classNames as props. Defaults to null.

function CustomTag({ classNames, tag, ...tagProps }) {
  return (
    <button type="button" className={classNames.tag} {...tagProps}>
      <span className={classNames.tagName}>{tag.label}</span>
    </button>
  )
}

selected (optional)

An array of selected tags. Each tag is an object which must have a value and a label property. Defaults to [].

const tags = [
  { value: 1, label: 'Apples' },
  { value: 2, label: 'Pears' },
]

For TypeScript users the TagSelected type can be extended with additional properties:

import type { TagSelected } from 'react-tag-autocomplete'
type CustomTagSelected = TagSelected & { myProperty: string }
const [selected, setSelected] = useState<CustomTagSelected[]>([])

suggestions (optional)

An array of tags for the user select. Each suggestion is an object which must have a value and a label property. Suggestions may also specify a disabled property to make the suggestion non-selectable. Defaults to [].

const suggestions = [
  { value: 3, label: 'Bananas' },
  { value: 4, label: 'Mangos' },
  { value: 5, label: 'Lemons' },
  { value: 6, label: 'Apricots', disabled: true },
]

For TypeScript users the TagSuggestion type can be extended with additional properties:

import type { TagSuggestion } from 'react-tag-autocomplete'
type CustomTagSuggestion = TagSuggestion & { myProperty: string }
const suggestions: CustomTagSuggestion[] = []

suggestionsTransform (optional)

Callback function to apply a custom filter to the list of suggestions. The callback receives two arguments; the current input value and the array of suggestions and must return a new array of suggestions. Using this prop you could sort suggestions or change the number of suggestions. Example:

import matchSorter from 'match-sorter'

function suggestionsTransform(value, suggestions) {
  return matchSorter(suggestions, value, { keys: ['label'] })
}

tagListLabelText (optional)

The ARIA label text added to the selected tags list. Defaults to "Selected tags".

API

By adding a ref to any instances of this component you can access its API methods.

const api = useRef(null)

<ReactTags ref={api} />

<button type="button" onClick={() => api.current.input.focus()}>
  Focus input
</button>

input.blur()

Removes cursor focus from the input.

input.focus()

Moves cursor focus to the input.

input.value

A getter/setter for the input value. If attempting to set a non-string value it will be stringified.

listBox.collapse()

Collapses the listbox if currently expanded.

listBox.expand()

Expands the listbox if currently collapsed.

listBox.activeOption

A getter for the currently active option.

listBox.isExpanded

A getter for the current listbox state. Returns a suggested option or null.

select()

Triggers the select function to add or remove the currently highlighted option.

Styling

It is possible to customize the appearance of the component using CSS, the included styles found in /example/styles.css are only an example. Custom class names can be provided to the component via the classNames prop.

Development

This project is written using TypeScript, Prettier for code formatting, ESLint for static analysis, and is tested with Vitest and Testing Library.

License

This project is ISC licensed. You are free to modify and distribute this code in private or commercial projects but the license and copyright notice must remain.