useState
williamsidewalk opened this issue · 4 comments
williamsidewalk commented
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
Hello, yes the component works just as well with useState()
as with class based components.
williamsidewalk commented
do you have an example that you can kindly share using hooks? I would like to use controlled components.
kulahin commented
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
Thank you for taking the time to share this example @kulahin