React hook form append custom key value
I have a form with an input type text, I can add text and click on enter to add the value to an array.
I want to save the data from the array to my form, but currently
tags
is still undefined once I submit.
Any ideas what I may be missing?
export default function TagInput() {
const [tags, setTags] = useState<string[]>([])
const [fullTags, setFullTags] = useState<string>('')
const { control, register } = useForm()
const { isSubmitting, errors } = useFormState()
const { fields, append, prepend, remove, swap, move, insert } = useFieldArray(
{
control, // control props comes from useForm (optional: if you are using FormContext)
name: 'tags', // unique name for your Field Array
}
)
const addTag = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === ',' || event.key === 'Enter') {
event.preventDefault()
const tagName = event.currentTarget.value.trim()
if (tagName !== '' && !tags.includes(tagName)) {
setTags((array) => [...array, tagName])
// save each tags comma separated to a new string
setFullTags((string) => string + tagName + ',')
// append to full tags as "tags" field
append({ name: fullTags })
}
event.currentTarget.value = ''
}
}
const deleteTag = (tag: string) => {
const newTags = tags.filter((t) => t !== tag)
setTags(newTags)
}
return (
<>
<div className="grid grid-cols-6 gap-6">
<div className="col-span-6 sm:col-span-3">
<Label htmlFor="tags">Tags</Label>
<Input
onKeyDown={(event) => addTag(event)}
export default function TagInput() {
const [tags, setTags] = useState<string[]>([])
const [fullTags, setFullTags] = useState<string>('')
const { control, register } = useForm()
const { isSubmitting, errors } = useFormState()
const { fields, append, prepend, remove, swap, move, insert } = useFieldArray(
{
control, // control props comes from useForm (optional: if you are using FormContext)
name: 'tags', // unique name for your Field Array
}
)
const addTag = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === ',' || event.key === 'Enter') {
event.preventDefault()
const tagName = event.currentTarget.value.trim()
if (tagName !== '' && !tags.includes(tagName)) {
setTags((array) => [...array, tagName])
// save each tags comma separated to a new string
setFullTags((string) => string + tagName + ',')
// append to full tags as "tags" field
append({ name: fullTags })
}
event.currentTarget.value = ''
}
}
const deleteTag = (tag: string) => {
const newTags = tags.filter((t) => t !== tag)
setTags(newTags)
}
return (
<>
<div className="grid grid-cols-6 gap-6">
<div className="col-span-6 sm:col-span-3">
<Label htmlFor="tags">Tags</Label>
<Input
onKeyDown={(event) => addTag(event)}
0 Replies