saagie-ui
Version:
Saagie UI from Saagie Design System
106 lines (93 loc) • 2.33 kB
JavaScript
import React from 'react';
import PropTypes from 'prop-types';
import { withFormsy, propTypes as formsyPropTypes } from 'formsy-react';
import { FormGroup } from '../../core/molecules/formGroup/FormGroup';
const propTypes = {
...formsyPropTypes,
children: PropTypes.node,
disabled: PropTypes.bool,
/**
* Object of props passed to the <FormGroup> component
*/
groupProps: PropTypes.object,
helper: PropTypes.node,
label: PropTypes.node,
onChange: PropTypes.func,
placeholder: PropTypes.string,
/**
* Object of props passed to the <textarea> element
*/
textareaProps: PropTypes.object,
};
const defaultProps = {
children: null,
disabled: false,
groupProps: {},
helper: null,
label: null,
onChange: () => {},
placeholder: null,
textareaProps: {},
};
export const FieldTextareaUI = ({
// Formsy props
errorMessage,
value,
isFormSubmitted,
isPristine,
isRequired,
isValid,
setValue,
// Global props
children,
disabled,
groupProps,
helper,
label,
onChange,
placeholder,
// Custom props
textareaProps,
}) => {
const [isTouched, setIsTouched] = React.useState(false);
const [isFocused, setIsFocused] = React.useState(false);
const isFeedbackVisible = (isTouched && !isPristine) || isFormSubmitted;
const isError = !isValid && isFeedbackVisible;
const handleChange = (event) => {
const val = event.currentTarget.value.trim();
setValue(val);
onChange(val);
};
const handleFocus = () => {
setIsFocused(true);
setIsTouched(true);
};
const handleBlur = () => {
setIsFocused(false);
};
return (
<FormGroup
label={label}
helper={helper}
isOptional={!isRequired}
validationState={!isFocused && isError ? 'danger' : null}
feedbackMessage={isFeedbackVisible && errorMessage}
{...groupProps}
>
<textarea
className="sui-a-form-control"
disabled={disabled}
placeholder={placeholder}
defaultValue={value || ''}
onChange={handleChange}
onFocus={handleFocus}
onBlur={handleBlur}
{...textareaProps}
/>
{children}
</FormGroup>
);
};
FieldTextareaUI.propTypes = propTypes;
FieldTextareaUI.defaultProps = defaultProps;
export const FieldTextarea = withFormsy(FieldTextareaUI);