-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiChipInput.tsx
More file actions
104 lines (94 loc) · 2.86 KB
/
Copy pathMultiChipInput.tsx
File metadata and controls
104 lines (94 loc) · 2.86 KB
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
import { Styled } from "./MultiChipInput.styled";
import { FC, useState, KeyboardEvent, ChangeEvent, useRef } from "react";
import { MultiChipInputProps } from "@sdge-components/MultiChipInput/MultiChipInput.types";
import { Box } from "@mui/material";
const MultiChipInput: FC<MultiChipInputProps> = ({
label,
onChange,
value = [],
errorMessage,
}) => {
const [inputValue, setInputValue] = useState<string>("");
const [inputFocused, setInputFocused] = useState<boolean>(false);
const inputRef = useRef(null);
const labelActive = value.length > 0 || inputValue !== "" || inputFocused;
const emailsSymbolsMax = inputValue.length > 45;
const handleSetChipValue = () => {
setInputFocused(false);
if (!value.includes(inputValue) && inputValue.trim() && !emailsSymbolsMax) {
onChange([...value, inputValue]);
setInputValue("");
}
};
const handleSetChipValueWithEnter = (e: KeyboardEvent<HTMLInputElement>) => {
if (
!value.includes(inputValue) &&
inputValue.trim() &&
e.which === 13 &&
!emailsSymbolsMax
) {
onChange([...value, inputValue]);
setInputValue("");
}
if (e.which === 8 && inputValue === "") {
const tempState = value.slice();
tempState.pop();
onChange(tempState);
}
};
const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
setInputValue(e.target.value);
};
const handleDeleteChip = (index: number) => {
const tempState = value.slice();
tempState.splice(index, 1);
onChange(tempState);
};
const handleInputFocus = () => {
setInputFocused(true);
};
return (
<Box>
<label>
<Styled.ChipFormControl
component="fieldset"
isActive={labelActive}
isError={!!errorMessage}
>
{label && (
<Styled.Label isActive={labelActive} isError={!!errorMessage}>
{label}
</Styled.Label>
)}
<Styled.Content>
{value.map((item: string, index: number) => {
return (
<Styled.Chip
label={item}
key={item}
onDelete={() => handleDeleteChip(index)}
/>
);
})}
<Styled.Input
name="input"
onBlur={handleSetChipValue}
onFocus={handleInputFocus}
onChange={handleInputChange}
onKeyDown={handleSetChipValueWithEnter}
value={inputValue}
autoComplete="off"
ref={inputRef}
/>
</Styled.Content>
</Styled.ChipFormControl>
</label>
{(!!errorMessage || emailsSymbolsMax) && (
<Styled.Error>
{emailsSymbolsMax ? "Email can has only 45 symbols" : errorMessage}
</Styled.Error>
)}
</Box>
);
};
export default MultiChipInput;