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

Top comments (0)