i-like-robots / react-tags

⚛️ Legacy repo for the fantastically simple tagging component for your React projects (legacy repo)
http://i-like-robots.github.io/react-tags
MIT License
457 stars 171 forks source link

useState #234

Closed williamsidewalk closed 3 years ago

williamsidewalk commented 3 years ago

Is there a way to use hooks and state with this library? I did not saw any examples on the documentation.

i-like-robots commented 3 years ago

Hello, yes the component works just as well with useState() as with class based components.

williamsidewalk commented 3 years ago

do you have an example that you can kindly share using hooks? I would like to use controlled components.

kulahin commented 3 years ago

do you have an example that you can kindly share using hooks? I would like to use controlled components.

import React, { useState, useRef } from 'react'

export default function MyForm() {

  const tagsInput = useRef(null);

  const [tags, setTags] = useState([]);
  const [suggestions, setSuggestions] = useState([]);
  const [tagAutocompleteBusy, setTagAutocompleteBusy] = useState(false);

  async function onTagInput(query) {
      if (!tagAutocompleteBusy) {
          setTagAutocompleteBusy(true);
          const result = await fetch(`/tags/autocomplete?term=${query}`);
          setSuggestions(result.data);
          setTagAutocompleteBusy(false);
          return result;
      }
  }

  const onTagDelete = (i) => {
      setTags(() => {
          tags.splice(i, 1);
          return tags;
      });
  }

  const onTagAddition = (tag) => {
      setTags(() => {
          return [...tags, tag];
      });
  }

  return (<>
    <ReactTags
        ref={tagsInput}
        tags={tags}
        suggestions={suggestions}
        onDelete={onTagDelete}
        onAddition={onTagAddition}
        onInput={onTagInput}
    />
  </>);
}
i-like-robots commented 3 years ago

Thank you for taking the time to share this example @kulahin