DEV Community

Aayush
Aayush

Posted on

Creating a tag input field in React.

So a tag input field as you may have guessed, will be used to store tags. Users shall be able to add/remove a collection of items or labels.

Heres the code in React.

const TagInput = () => {
  const [text, setText] = useState("");

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

  useEffect(() => {
    if (text.charAt(text.length - 1) === ",") {
      const tag = text.slice(0, text.length - 1);
      if (tag && !tags.includes(tag)) setTags((prevTags) => [tag, ...prevTags]);

      setText("");
    }
  }, [text, tags]);

  const removeTag = (tag: string) => {
    setTags((tags) => tags.filter((t) => t !== tag));
  };

  return (
    <div>
      <label htmlFor="tags">Tags (seperated by comma)</label>
      <div className="flex min-h-16 w-full flex-wrap rounded-lg border-2 border-gray-300 p-3 text-sm">
        {tags.map((tag, i) => (
          <div
            key={tag+i}
            className="mr-2 inline-flex items-center gap-1 rounded-sm bg-gray-200 px-2 py-1"
          >
            <span>{tag}</span>
            <span
              onClick={() => removeTag(tag)}
              className="grid size-6 cursor-pointer place-content-center rounded-full bg-gray-300 duration-200 ease-out hover:bg-zinc-300"
            >
              X
            </span>
          </div>
        ))}
        <input
          value={text}
          onChange={(e) => setText(e.target.value)}
          id="tags"
          type="text"
          placeholder="e.g. blood, stress, nutrition"
          className="grow outline-none"
        />
      </div>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more