-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathfield-label.component.tsx
59 lines (52 loc) · 1.77 KB
/
field-label.component.tsx
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
import React from 'react';
import { Tooltip as CarbonTooltip } from '@carbon/react';
import { useTranslation } from 'react-i18next';
import { type FormField } from '../../types';
import styles from './field-label.scss';
import { Information } from '@carbon/react/icons';
interface FieldLabelProps {
field: FormField;
/**
* Custom label text to override the default field label.
*/
customLabel?: string;
}
const Tooltip: React.FC<{ field: FormField; children: React.ReactNode }> = ({ field, children }) => {
const { t } = useTranslation();
return (
<CarbonTooltip align="top-left" label={t(field.questionInfo)} defaultOpen>
{children}
</CarbonTooltip>
);
};
interface FieldLabelContentProps extends FieldLabelProps {
hasTooltip: boolean;
}
const FieldLabelContent: React.FC<FieldLabelContentProps> = ({ field, customLabel, hasTooltip }) => {
const { t } = useTranslation();
const labelText = customLabel || t(field.label);
return (
<div className={styles.questionLabel} data-testid={`${field.id}-label`}>
<span>{labelText}</span>
{field.isRequired && (
<span title={t('required', 'Required')} className={styles.required}>
*
</span>
)}
{hasTooltip && (
<Information size={20} aria-hidden="true" className={styles.tooltipIcon} data-testid="information-icon" />
)}
</div>
);
};
const FieldLabel: React.FC<FieldLabelProps> = ({ field, customLabel }) => {
const hasTooltip = Boolean(field.questionInfo);
return hasTooltip ? (
<Tooltip field={field}>
<FieldLabelContent field={field} customLabel={customLabel} hasTooltip={hasTooltip} />
</Tooltip>
) : (
<FieldLabelContent field={field} customLabel={customLabel} hasTooltip={hasTooltip} />
);
};
export default FieldLabel;