-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathContactFields.tsx
More file actions
101 lines (95 loc) · 2.37 KB
/
ContactFields.tsx
File metadata and controls
101 lines (95 loc) · 2.37 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
import {
Control,
FieldValues,
useFieldArray,
UseFormGetValues,
UseFormRegister,
} from "react-hook-form";
import { Row, Col, Button, Icon } from "@canonical/react-components";
type Props = {
register: UseFormRegister<FieldValues>;
control: Control<FieldValues>;
labelName: string;
fieldName: string;
getValues: UseFormGetValues<FieldValues>;
};
function ContactFields({
register,
control,
labelName,
fieldName,
getValues,
}: Props): React.JSX.Element {
const { fields, append, remove } = useFieldArray({
control,
name: fieldName,
});
return (
<>
{fields.length === 0 && (
<Row className="p-form__group">
<Col size={2}>
<label htmlFor={fieldName}>{labelName}:</label>
</Col>
<Col size={5}>
<Button
type="button"
appearance="link"
onClick={() => {
append({ url: "" });
}}
>
+ Add field
</Button>
</Col>
</Row>
)}
{fields.map((field, index) => (
<Row className="p-form__group" key={field.id}>
{index === 0 && (
<Col size={2}>
<label htmlFor={fieldName}>{labelName}:</label>
</Col>
)}
<Col size={5} emptyLarge={index === 0 ? undefined : 3}>
<div className="p-form__control">
<input
type="url"
{...register(`${fieldName}.${index}.url`)}
defaultValue={getValues(`${fieldName}.${index}.url`)}
/>
</div>
</Col>
<Col size={2}>
<Button
type="button"
appearance="base"
onClick={() => {
remove(index);
}}
>
<Icon name="delete" />
<span className="u-off-screen">Remove this link</span>
</Button>
</Col>
</Row>
))}
{fields.length > 0 && (
<Row>
<Col size={5} emptyLarge={3}>
<Button
type="button"
appearance="link"
onClick={() => {
append({ url: "" });
}}
>
+ Add field
</Button>
</Col>
</Row>
)}
</>
);
}
export default ContactFields;