-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathFormElement.tsx
More file actions
103 lines (94 loc) · 2.38 KB
/
FormElement.tsx
File metadata and controls
103 lines (94 loc) · 2.38 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
// Libraries
import React, {forwardRef} from 'react'
import classnames from 'classnames'
// Components
import {FormLabel} from './FormLabel'
import {FormElementError} from './FormElementError'
import {FormHelpText} from './FormHelpText'
// Types
import {StandardFunctionProps} from '../../Types'
export interface FormElementProps extends StandardFunctionProps {
/** Label Text */
label: string
/** Input instruction text */
helpText?: string
/** Text to be displayed on error */
errorMessage?: string
/** Element to be displayed along with label */
labelAddOn?: () => JSX.Element
/** Whether this field is required to submit form, adds red required asterisk */
required?: boolean
/** Useful for associating a label with an input */
htmlFor?: string
/** ID for Error Message for Integration Tests */
errorMessageTestId?: string
}
export type FormElementRef = HTMLLabelElement & HTMLDivElement
export const FormElement = forwardRef<FormElementRef, FormElementProps>(
(
{
id,
label,
style,
htmlFor,
required,
helpText,
children,
className,
labelAddOn,
errorMessage,
testID = 'form--element',
errorMessageTestId,
},
ref
) => {
const formElementClass = classnames('cf-form--element', {
[`${className}`]: className,
})
const formElementElements = (
<>
{!!label && (
<FormLabel label={label} required={required}>
{!!labelAddOn && labelAddOn()}
</FormLabel>
)}
{children}
<div className="cf-form--element-error-container">
{!!errorMessage && (
<FormElementError
testID={errorMessageTestId}
message={errorMessage}
/>
)}
{!!helpText && !errorMessage && <FormHelpText text={helpText} />}
</div>
</>
)
if (htmlFor) {
return (
<label
id={id}
ref={ref}
style={style}
htmlFor={htmlFor}
data-testid={testID}
className={formElementClass}
>
{formElementElements}
</label>
)
}
return (
<div
id={id}
ref={ref}
style={style}
data-testid={testID}
className={formElementClass}
>
{formElementElements}
</div>
)
}
)
FormElement.displayName = 'FormElement'