All files / src/components/Inputs/InputTypes StringArrayInput.tsx

0% Statements 0/23
0% Branches 0/10
0% Functions 0/8
0% Lines 0/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73                                                                                                                                                 
import { HTMLInputTypeAttribute, useState } from "react";
import CustomInput from "../CustomInput";
import { InputTypes } from "../../../types";
import CustomButton from "../../common/CustomButton";
import { Add, Delete } from "@mui/icons-material";
 
type StringArrayInputTypes = {
  label?: string;
  value: string[];
  handleChange: (val: string) => void;
  error?: string;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
  type?: HTMLInputTypeAttribute;
} & React.InputHTMLAttributes<HTMLInputElement>;
 
function StringArrayInput({
  label,
  placeholder,
  disabled,
  ...props
}: StringArrayInputTypes) {
  const [values, setValues] = useState<string[]>(props.value ?? [""]);
 
  const handleAddClick = () => {
    setValues([...values, ""]);
  };
 
  const handleDelete = (index: number) => {
    const newValues = values.filter((_, i) => i !== index);
    setValues(newValues);
    props.handleChange(JSON.stringify(newValues));
  };
 
  const handleValueChange = (val: string, index: number) => {
    const newValues = [...values];
    newValues[index] = val;
    setValues(newValues);
    props.handleChange(JSON.stringify(newValues));
  };
 
  return (
    <div className="flex flex-col gap-2">
      {values.map((value, index) => (
        <div className="flex flex-wrap gap-2">
          <CustomInput
            {...props}
            value={value}
            handleChange={(val: string) => handleValueChange(val, index)}
            inputType={InputTypes.TEXT}
            label={undefined}
            placeholder={placeholder ?? `${label}`}
            className="!w-[200px]"
          />
          {!disabled && index > 0 && (
            <CustomButton onClick={() => handleDelete(index)}>
              <Delete fontSize="small" />
            </CustomButton>
          )}
          {!disabled && index === values.length - 1 && (
            <CustomButton onClick={handleAddClick}>
              <Add fontSize="small" />
            </CustomButton>
          )}
        </div>
      ))}
    </div>
  );
}
 
export default StringArrayInput;