import { classNames } from '@/utils'; import { ChangeEventHandler, KeyboardEventHandler, useState } from 'react'; import { HiExclamationCircle } from 'react-icons/hi'; import ErrorMessage from './ErrorMessage'; export interface MultipleTextInputProps { id?: string; className?: string; label?: string; errors?: string[] | undefined; placeholder?: string; value: string[]; setValue: (values: string[]) => void; helpText?: string; } const MultipleTextInput = ({ id, className, label, errors, placeholder, value, setValue, helpText, }: MultipleTextInputProps) => { const [inputValue, setInputValue] = useState(''); // Set only uniquer value const setNewValue = (newValue: string) => { const uniqueValues = [...value, newValue].filter(function (elem, index, self) { return index === self.indexOf(elem); }); setValue(uniqueValues); }; // Set inputValue on change const handleInputChange: ChangeEventHandler = (event) => { setInputValue(event.target.value); }; // Add text on enter/tab const handleKeyDown: KeyboardEventHandler = (event) => { if (event.key == 'Backspace' && inputValue == '') { const values = [...value]; setValue( values.filter((item, i) => { item; i !== values.length - 1; }) ); event.preventDefault(); return; } if (!inputValue) return; if (event.key == 'Enter' || event.key == 'Tab') { setNewValue(inputValue); setInputValue(''); event.preventDefault(); return; } }; // Remove text const remove = (index: number) => { const values = [...value]; const newValues = values.filter((_, i) => i !== index); setValue(newValues); }; const hasErrors = Boolean(errors && errors.length > 0); const componentId = id || Math.random().toString(); const validClasses = 'border border-gray-300 placeholder-gray-400 focus-within:ring-1 focus-within:ring-primary-500 focus-within:border-primary-500'; const errorClasses = 'border border-red-300 text-red-900 placeholder-red-300 focus-within:ring-1 focus-within:ring-danger-500 focus-within:border-danger-500 hasErrors'; return ( <> {label && ( )}
{value.map((item, index) => { return (
{item}
); })} {hasErrors && (
)}
{helpText && {helpText}} ); }; export default MultipleTextInput;