fix: TagInput component values initialization

This commit is contained in:
Flavio Mastrangelo 2025-02-25 20:40:39 +01:00
parent 60ae7706bd
commit 593177f6e1

View file

@ -1,4 +1,4 @@
import React, { useState, Dispatch, SetStateAction } from 'react' import React, { useState, Dispatch, SetStateAction, useEffect } from 'react'
import { Tag, TagInput } from 'emblor' import { Tag, TagInput } from 'emblor'
interface FormTagInputProps { interface FormTagInputProps {
@ -16,14 +16,29 @@ const FormTagInput = ({
error, error,
placeholder, placeholder,
}: FormTagInputProps) => { }: FormTagInputProps) => {
const initialTags = value const [tags, setTags] = useState<Tag[]>(() =>
? value.split(separator).map((text, i) => ({ value && typeof value === 'string'
id: i.toString(), ? value.split(separator).filter(text => text.trim()).map((text, i) => ({
text: text.trim(), id: i.toString(),
})) text: text.trim(),
: [] }))
: []
);
useEffect(() => {
if (value && typeof value === 'string') {
const newTags = value.split(separator)
.filter(text => text.trim())
.map((text, i) => ({
id: i.toString(),
text: text.trim(),
}));
setTags(newTags);
} else {
setTags([]);
}
}, [value, separator]);
const [tags, setTags] = useState<Tag[]>(initialTags)
const [activeTagIndex, setActiveTagIndex] = useState<number | null>(null) const [activeTagIndex, setActiveTagIndex] = useState<number | null>(null)
const handleTagsChange: Dispatch<SetStateAction<Tag[]>> = ( const handleTagsChange: Dispatch<SetStateAction<Tag[]>> = (