| 1 |
import { useRef, useState } from 'react'; |
| 2 |
import { Form, FormGroup, FormHelperText, HelperText, HelperTextItem, TextArea } from '@patternfly/react-core'; |
| 3 |
|
| 4 |
export const TextAreaValidated: React.FunctionComponent = () => { |
| 5 |
const [value, setValue] = useState(''); |
| 6 |
const [validated, setValidated] = useState<'default' | 'error' | 'warning' | 'success' | undefined>('default'); |
| 7 |
const [helperText, setHelperText] = useState('Share your thoughts.'); |
| 8 |
const timerRef = useRef<number | null>(null); |
| 9 |
const simulateNetworkCall = (callback: Function) => { |
| 10 |
if (timerRef.current) { |
| 11 |
clearTimeout(timerRef.current); |
| 12 |
} |
| 13 |
timerRef.current = setTimeout(callback, 2000); |
| 14 |
}; |
| 15 |
|
| 16 |
const handleTextAreaChange = (value: string) => { |
| 17 |
setValue(value); |
| 18 |
setValidated('default'); |
| 19 |
setHelperText('Validating...'); |
| 20 |
simulateNetworkCall(() => { |
| 21 |
if (value.length > 0) { |
| 22 |
if (value.length >= 10) { |
| 23 |
setValidated('success'); |
| 24 |
setHelperText('Thanks for your comments!'); |
| 25 |
} else { |
| 26 |
setValidated('error'); |
| 27 |
setHelperText("You're being too brief, please enter at least 10 characters."); |
| 28 |
} |
| 29 |
} else { |
| 30 |
setValidated('warning'); |
| 31 |
setHelperText('You must have something to say'); |
| 32 |
} |
| 33 |
}); |
| 34 |
}; |
| 35 |
return ( |
| 36 |
<Form> |
| 37 |
<FormGroup label="Comments:" type="string" fieldId="selection"> |
| 38 |
<TextArea |
| 39 |
value={value} |
| 40 |
onChange={(_event, value) => handleTextAreaChange(value)} |
| 41 |
isRequired |
| 42 |
validated={validated} |
| 43 |
aria-label="invalid text area example" |
| 44 |
/> |
| 45 |
<FormHelperText> |
| 46 |
<HelperText> |
| 47 |
<HelperTextItem variant={validated}>{helperText}</HelperTextItem> |
| 48 |
</HelperText> |
| 49 |
</FormHelperText> |
| 50 |
</FormGroup> |
| 51 |
</Form> |
| 52 |
); |
| 53 |
}; |