UNPKG

saagie-ui

Version:

Saagie UI from Saagie Design System

117 lines (104 loc) 2.74 kB
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, displayType: PropTypes.oneOf(['default', 'button', 'button-light', 'button-denim-300', 'toggle']), formCheckClassName: PropTypes.string, /** * Object of props passed to the <FormGroup> component */ groupProps: PropTypes.object, helper: PropTypes.node, /** * Object of props passed to the <input> element */ inputProps: PropTypes.object, label: PropTypes.node, message: PropTypes.node, onChange: PropTypes.func, }; const defaultProps = { children: null, disabled: false, displayType: 'default', formCheckClassName: '', groupProps: {}, helper: null, inputProps: {}, label: null, message: '', onChange: () => {}, }; export const FieldCheckUI = ({ // Formsy props errorMessage, value, isFormSubmitted, isPristine, isRequired, isValid, setValue, // Global props children, disabled, groupProps, helper, label, onChange, // Custom props formCheckClassName, inputProps, message, displayType, }) => { 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 isChecked = !!event.currentTarget.checked; setValue(isChecked); onChange(isChecked); }; 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} > <label className={`sui-a-form-check as--${displayType} ${formCheckClassName}`}> <input type="checkbox" defaultChecked={value || false} disabled={disabled} onChange={handleChange} onFocus={handleFocus} onBlur={handleBlur} {...inputProps} /> <span className="sui-a-form-check__indicator" /> <span className="sui-a-form-check__label"> {message} </span> </label> {children} </FormGroup> ); }; FieldCheckUI.propTypes = propTypes; FieldCheckUI.defaultProps = defaultProps; export const FieldCheck = withFormsy(FieldCheckUI);