hc-oss / react-tag-input-component

lightweight react component for tag(s) input
https://codesandbox.io/s/react-tag-input-component-rgf97
MIT License
82 stars 37 forks source link

Feature Request: maxLength #55

Open clipartinc opened 1 year ago

clipartinc commented 1 year ago

Add the maxLength attribute.

tomyedlp commented 11 months ago

Not the best case but you can do this:


const [availableKeywords, setAvailableKeywords] = useState<string>("Max. 10 keywords")

useEffect(() => {
   setAvailableKeywords(keywords.length === 0 ? `Max. 10 keywords` : `${10-keywords.length} keywords left`)
}, [keywords])

const checkMaxLengthkeywords = () => {
   return keywords.length < 10 ? true : false
}

return (
  <TagsInput
      classNames={{tag: 'keywordTag', input: 'inputImg'}}
      value={keywords}
      onChange={setKeywords}
      name="keywords"
      separators={["Enter",","]}
      placeHolder={availableKeywords}
      beforeAddValidate={checkMaxLengthkeywords}
  />
)
freitassdev commented 1 month ago

you can use something like:


import React, { useCallback, useEffect, useState } from 'react';
import { TagsInput } from "react-tag-input-component";
import toast from 'react-hot-toast';

export default function YourComponent() {
    const [tags, setTags] = useState(["dev", "nextjs"]);

    useEffect(() => {
        if(tags.length > 8) {
            setTags(tags.slice(0, 8));
            toast.error("max 8 tags."); //you can use other toast lib or other way to display the message to user
        }
    }, [tags]);

    return (
        <>
                <TagsInput
                    value={tags}
                    onChange={setTags}
                    name="tags"
                    placeHolder="write the tags"
                    separators={[",", "Enter"]}

                />
        </>

    );
};```