summaryrefslogtreecommitdiffstats
path: root/src/components/FormElements/Field/Field.tsx
blob: c8df0f9ba2d5df6822b58f39210e5d8eeaa4cee4 (plain)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import {
  ChangeEvent,
  ForwardedRef,
  forwardRef,
  ReactElement,
  SetStateAction,
} from 'react';
import styles from './Field.module.scss';

type FieldType = 'email' | 'number' | 'search' | 'select' | 'text' | 'textarea';
type SelectOptions = {
  id: string;
  name: string;
  value: string;
};

const Field = (
  {
    id,
    name,
    value,
    setValue,
    required = false,
    kind = 'text',
    label,
    options,
  }: {
    id: string;
    name: string;
    value: string;
    setValue: (value: SetStateAction<string>) => void;
    required?: boolean;
    kind?: FieldType;
    label?: ReactElement;
    options?: SelectOptions[];
  },
  ref: ForwardedRef<HTMLInputElement | HTMLTextAreaElement>
) => {
  const updateValue = (
    e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>
  ) => {
    setValue(e.target.value);
  };

  const getOptions = () => {
    return options
      ? options.map((option) => (
          <option key={option.id} value={option.value}>
            {option.name}
          </option>
        ))
      : '';
  };

  const getField = () => {
    switch (kind) {
      case 'select':
        return (
          <select
            name={name}
            id={id}
            value={value}
            onChange={updateValue}
            required={required}
            className={`${styles.field} ${styles.select}`}
          >
            {getOptions()}
          </select>
        );
      case 'textarea':
        return (
          <textarea
            ref={ref as ForwardedRef<HTMLTextAreaElement>}
            id={id}
            name={name}
            value={value}
            required={required}
            onChange={updateValue}
            className={`${styles.field} ${styles.textarea}`}
          />
        );
      default:
        return (
          <input
            ref={ref as ForwardedRef<HTMLInputElement>}
            type={kind}
            id={id}
            name={name}
            value={value}
            required={required}
            onChange={updateValue}
            className={styles.field}
          />
        );
    }
  };

  return (
    <>
      {label}
      {getField()}
    </>
  );
};

export default forwardRef(Field);