1.2.0 • Published 3 years ago

react-autocomplete-tag v1.2.0

Weekly downloads
8
License
MIT
Repository
github
Last release
3 years ago

react-autocomplete-tag

A simple autocomplete tagging component for react app with typescript support

NPM JavaScript Style Guide

Screenshot 1

Screenshot 1

Screenshot 2

Screenshot 2

Requirements

  • react: ^16.0.0

Features

  • Autocomplete based on suggestion list
  • Keyboard friendly and mouse support

Install

npm install --save react-autocomplete-tag

Usage

import React, { useState } from 'react'

import ReactTags from 'react-autocomplete-tag' // load ReactTags component
import 'react-autocomplete-tag/dist/index.css' // load default style

const App = () => {
  const tagList: string[] = [
    'America',
    'Argentina',
    'Africa',
    'Bangladesh',
    'Burma',
    'China',
    'Chile',
    'Denmark',
    'England'
  ]

  var [tags, setTags] = useState<string[]>([])

  const [suggestions, setSuggestions] = useState<string[]>([])

  const addTag = (val: string) => {
    setTags([...tags, val])
    setSuggestions([])
  }

  const removeTag = (idx: number) => {
    var t = [...tags]
    t.splice(idx, 1)
    setTags(t)
  }

  const handleTagChange = (val: string) => {
    // in real app, suggestions could be fetched from backend

    if (val.length > 0) {
      var new_sug: string[] = []
      tagList.forEach((t) => {
        if (t.includes(val)) {
          new_sug.push(t)
        }
      })
      setSuggestions(new_sug)
    } else {
      setSuggestions([])
    }
  }

  return (
    <ReactTags
      tags={tags}
      suggestions={suggestions}
      onAddHandler={(val: string) => addTag(val)}
      onDeleteHandler={(idx: number) => removeTag(idx)}
      onChangeHandler={(val: string) => handleTagChange(val)}
    />
  )
}

export default App

Options

OptionTypeDefault ValueRequire / OptionalDescription
tagsArray of String[]RequireAn array of tags that are displayed as pre-selected
suggestionsArray of String[]RequireAn array of suggestions
placeholderStringEnter a tagOptionalThe placeholder for tag input
delimetersArray of String"Enter", ","OptionalSpecifies which characters should terminate tags input
onAddHandlerFunctionundefinedRequireFunction called when the user wants to add a tag
onDeleteHandlerFunctionundefinedRequireFunction called when the user deletes a tag
onChangeHandlerFunctionundefinedOptionalFunction called when the tag input value change. You can fetch the suggestions from backend based on tag input value and update su

License

MIT © joenayjoe