• Stars
    star
    457
  • Rank 95,775 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 9 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

⚛️ Legacy repo for the fantastically simple tagging component for your React projects (legacy repo)

React Tag Autocomplete

GitHub license build status Coverage Status npm version

React Tag Autocomplete is a simple tagging component ready to drop in your React projects. Originally based on the React Tags project by Prakhar Srivastav this version removes the drag-and-drop re-ordering functionality, adds appropriate roles and ARIA states and introduces a resizing text input. View demo.

Screenshot of React Tag Autocomplete

Please note: Version 7 of this component is under development, to view the upcoming version of React Tag Autocomplete please go to the new repository.

Installation

This is a Node.js module available through the npm registry. Before installing, download and install Node.js.

Installation is done using the npm install command:

npm install --save react-tag-autocomplete

Usage

Here's a sample implementation that initializes the component with an empty list of tags and a pre-populated list of suggestions. For further customization details, see options.

import React, { useCallback, useRef, useState } from 'react'
import ReactTags from 'react-tag-autocomplete'

function App () {
  const [tags, setTags] = useState([])

  const [suggestions, setSuggestions] = useState([
    { id: 1, name: "Apples" },
    { id: 2, name: "Pears" },
    { id: 3, name: "Bananas" },
    { id: 4, name: "Mangos" },
    { id: 5, name: "Lemons" },
    { id: 6, name: "Apricots" }
  ])

  const reactTags = useRef()

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

  const onAddition = useCallback((newTag) => {
    setTags([...tags, newTag])
  }, [tags])

  return (
    <ReactTags
      ref={reactTags}
      tags={tags}
      suggestions={suggestions}
      onDelete={onDelete}
      onAddition={onAddition}
    />
  )
}

Options

id (optional)

The ID attribute given to the listbox element. Default: ReactTags.

tags (optional)

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

const tags =  [
  { id: 1, name: 'Apples' },
  { id: 2, name: 'Pears' }
]

suggestions (optional)

An array of tag suggestions. Each suggestion is an object which must have an id and a name property and an optional disabled property to make the suggestion non-selectable. Defaults to [].

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

suggestionsFilter (optional)

A callback function to filter suggestion items with. The callback receives two arguments; a suggestion and the current query and must return a boolean value.

If no function is supplied the default filter is applied. Defaults to null.

Note: This filter will be ignored if suggestionsTransform is supplied.

suggestionsTransform (optional)

A callback function to apply a custom filter to the suggestions. The callback receives two arguments; a query and the input suggestions and must return a new array of suggestion items. Using this option you can filter and sort suggestions.

Note: This will supersede suggestionsFilter in future.

import matchSorter from "match-sorter";

function suggestionsFilter(query, suggestions) {
  return matchSorter(suggestions, query, { keys: ["name"] });
}

placeholderText (optional)

The placeholder string shown for the input. Defaults to 'Add new tag'.

ariaLabelText (optional)

The aria-label string for the input. Defaults to placeholder string.

removeButtonText (optional)

The title text to add to the remove selected tag button. Default 'Click to remove tag'.

noSuggestionsText (optional)

Message shown if there are no matching suggestions. Defaults to null.

newTagText (optional)

Enables users to show a prompt to add a new tag at the bottom of the suggestions list if allowNew is enabled. Defaults to null.

autoresize (optional)

Boolean parameter to control whether the text-input should be automatically resized to fit its value. Defaults to true.

delimiters (optional)

Array of keys matching KeyboardEvent.key values. When a corresponding key is pressed it will trigger tag selection or creation. Defaults to ['Enter', 'Tab'].

minQueryLength (optional)

Minimum query length required to show the suggestions list. Defaults to 2.

maxSuggestionsLength (optional)

Maximum number of suggestions to display. Defaults to 6.

classNames (optional)

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

{
  root: 'react-tags',
  rootFocused: 'is-focused',
  selected: 'react-tags__selected',
  selectedTag: 'react-tags__selected-tag',
  selectedTagName: 'react-tags__selected-tag-name',
  search: 'react-tags__search',
  searchWrapper: 'react-tags__search-wrapper',
  searchInput: 'react-tags__search-input',
  suggestions: 'react-tags__suggestions',
  suggestionActive: 'is-active',
  suggestionDisabled: 'is-disabled',
  suggestionPrefix: 'react-tags__suggestion-prefix'
}

onAddition (required)

Function called when the user wants to add a tag. Receives the tag.

const [tags, setTags] = useState([])

function onAddition (newTag) {
  setTags([...tags, newTag])
}

onDelete (required)

Function called when the user wants to delete a tag. Receives the tag index.

const [tags, setTags] = useState([])

function onDelete (tagIndex) {
  setTags(tags.filter((_, i) => i !== tagIndex))
}

onInput (optional)

Optional event handler when the input value changes. Receives the current query.

const [isBusy, setIsBusy] = useState(false)

function onInput (query) {
  if (!isBusy) {
    setIsBusy(true)

    return fetch(`?query=${query}`).then((result) => {
      setIsBusy(false)
    })
  }
}

onFocus (optional)

Optional callback function for when the input receives focus. Receives no arguments.

onBlur (optional)

Optional callback function for when focus on the input is lost. Receives no arguments.

onValidate (optional)

Optional validation function that determines if tag should be added. Receives the tag object and must return a boolean.

function onValidate (tag) {
  return tag.name.length >= 5;
}

addOnBlur (optional)

Creates a tag from the current input value when focus on the input is lost. Defaults to false.

allowNew (optional)

Enable users to add new (not suggested) tags. Defaults to false.

allowBackspace (optional)

Enable users to delete selected tags when backspace is pressed while focussed on the text input when empty. Defaults to true.

tagComponent (optional)

Provide a custom tag component to render. Receives the tag, button text, and delete callback as props. Defaults to null.

function TagComponent ({ tag, removeButtonText, onDelete }) {
  return (
    <button type='button' title={`${removeButtonText}: ${tag.name}`} onClick={onDelete}>
      {tag.name}
    </button>
  )
}

suggestionComponent (optional)

Provide a custom suggestion component to render. Receives the suggestion and current query as props. Defaults to null.

function SuggestionComponent ({ item, query }) {
  return (
    <span id={item.id} className={item.name === query ? 'match' : 'no-match'}>
      {item.name}
    </span>
  )
}

inputAttributes (optional)

An object containing additional attributes that will be applied to the text input. Please note that this prop cannot overwrite existing attributes, it can only add new ones. Defaults to {}.

API

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

addTag(tag)

Adds a tag to the list of selected tags. This will trigger the validation and addition callbacks.

deleteTag(index)

Removes a tag from the list of selected tags. This will trigger the delete callback.

clearInput()

Clears the input, current query and selected suggestion.

clearSelectedIndex()

Clears the currently selected suggestion.

focusInput()

Sets cursor focus to the text input element.

Styling

It is possible to customize the appearance of the component, the included styles found in /example/styles.css are only an example.

Development

The component is written in ES6 and uses Rollup as its build tool. Tests are written with Jasmine using JSDOM.

npm install
npm run dev # will open http://localhost:8080 and watch files for changes

Upgrading

To see all changes refer to the changelog.

Upgrading from 5.x to 6.x

  • React 16.5 or above is now required.
  • Event handlers and callbacks have been renamed to use on prefixes, e.g. the handleAddition() callback should now be called onAddition().
  • The delimiters option is now an array of KeyboardEvent.key values and not KeyboardEvent.keyCode codes, e.g. [13, 9] should now be written as ['Enter', 'Tab']. See https://keycode.info/ for more information.
  • The placeholder option has been renamed placeholderText
  • The ariaLabel option has been renamed ariaLabelText
  • The delimiterChars option has been removed, use the delimiters option instead.
  • The clearInputOnDelete option has been removed and is now the default behaviour
  • The autofocus option has been removed.

More Repositories

1

EasyZoom

🔎 EasyZoom is an elegant, highly optimised jQuery image zoom and panning plugin.
JavaScript
445
star
2

react-tube-tracker

🚇 An isomorphic React app to check the arrival times of trains on the Tube (from 2014)
JavaScript
259
star
3

react-tag-autocomplete

⚛️ A simple, accessible, tagging component ready to drop into your React projects (new repo)
TypeScript
165
star
4

Responsive-Image-Placeholders

Using a little basic CSS, JavaScript and a dash of animation it's simple to avoid the performance hit of re-calculating layout and provide a smooth user experience.
HTML
66
star
5

rewireify

Rewireify is a port of Rewire for Browserify that adds setter and getter methods to each module so that their behaviour can be modified for better unit testing.
JavaScript
60
star
6

hyperons

🔥 The fastest JSX to string renderer on the server and in the browser.
JavaScript
45
star
7

jQuery-Slideshow

jQuery Slideshow is a performant and developer friendly image slideshow and content carousel plugin. 2KB when gzipped.
JavaScript
41
star
8

grid-layout-demo

The FT.com front page re-created with CSS grid layout
CSS
34
star
9

WebsiteBase

WebsiteBase is more than a boilerplate, less than a framework and great place for front-end developers to start new projects. It combines ideas from OOCSS and SMACSS to help create an opinionated code base for scalable and maintainable website development.
CSS
13
star
10

express-request-mock

🖖 A convenient wrapper for node-mocks-http which makes testing Express controllers and middleware easy.
JavaScript
13
star
11

jQuery-Modal

Every front-end developer needs their own modal window. The plugin is optimised and customisable and even supports multiple, nestable instances.
JavaScript
13
star
12

svg-sprite-generator

An experimental SVG sprite generation service prototype
JavaScript
11
star
13

groundwork

A simple bootstrap for loading and binding DOM elements to JavaScript modules in an understandable way.
JavaScript
11
star
14

promise-patterns

🙌 Utility functions to help compose promise based code.
JavaScript
8
star
15

chai-html

☕️ A focussed HTML assertions plugin for Chai.
JavaScript
6
star
16

extract-css-block-webpack-plugin

I'll admit, it's not a catchy name.
JavaScript
6
star
17

preact-tube-tracker

🚇 A Preact and ES6 port of my original React Tube Tracker
CSS
5
star
18

rsvp

👰 An application to collect guest's RSVPs and contact details
Ruby
4
star
19

xslt-fiddle

A playground to test XSL transformations
CSS
4
star
20

hardened-fetch

🦾 Hardened Fetch is a tiny wrapper for `global.fetch` which makes working with APIs without SDKs and web scraping easier.
TypeScript
4
star
21

guestlist

🎫 Guestlist is a tiny library that whitelists, validates, and sanitizes HTTP request properties
JavaScript
3
star
22

reliable-module-ids-plugin

🆔 A Webpack plugin to generate more consistent module IDs
JavaScript
3
star
23

react-through-time

👴🏻 Following the evolution of a small React application over the last 8 years
CSS
2
star
24

lionel

🗞 The latest news from the Financial Times in your terminal.
JavaScript
2
star
25

ts-package-boilerplate

My personal boilerplate for new JavaScript/TypeScript projects.
TypeScript
2
star
26

get-package-name

📦 Extracts the name of a package from its file path.
JavaScript
2
star
27

groundwork-components

Dependency-free JavaScript modules compatible with but not limited to usage with GroundworkJS
JavaScript
1
star
28

accessibility-demos

HTML
1
star
29

elastic-reindex

A simple tool to reindex or move your Elasticsearch data using the scroll and bulk APIs
JavaScript
1
star