|
| 1 | +import React from 'react'; |
| 2 | +import PropTypes from 'prop-types'; |
| 3 | +import { Radio as AntRadio } from 'antd'; |
| 4 | +import { wrapperProps } from '@data-driven-forms/common/src/multiple-choice-list'; |
| 5 | +import AntForm from '../common/form-wrapper'; |
| 6 | +import { validationError } from '../common/helpers'; |
| 7 | +import { useFieldApi } from '@data-driven-forms/react-form-renderer'; |
| 8 | + |
| 9 | +const RadioOption = ({ name, option }) => { |
| 10 | + const { input } = useFieldApi({ name, type: 'radio', value: option.value }); |
| 11 | + return ( |
| 12 | + <AntRadio key={`${name}-${option.value}`} {...input} id={`${name}-${option.value}`}> |
| 13 | + {option.label} |
| 14 | + </AntRadio> |
| 15 | + ); |
| 16 | +}; |
| 17 | + |
| 18 | +RadioOption.propTypes = { |
| 19 | + name: PropTypes.string.isRequired, |
| 20 | + option: PropTypes.shape({ label: PropTypes.string.isRequired, value: PropTypes.any.isRequired }).isRequired |
| 21 | +}; |
| 22 | + |
| 23 | +const Radio = ({ name, ...props }) => { |
| 24 | + const { options, isDisabled, label, isRequired, helperText, description, isReadOnly, meta, validateOnMount } = useFieldApi({ |
| 25 | + ...props, |
| 26 | + name, |
| 27 | + type: 'radio' |
| 28 | + }); |
| 29 | + const invalid = validationError(meta, validateOnMount); |
| 30 | + const text = invalid || helperText || description; |
| 31 | + return ( |
| 32 | + <AntForm layout="vertical" isRequired={isRequired} label={label} invalid={invalid} help={text}> |
| 33 | + <AntRadio.Group name={name} disabled={isDisabled || isReadOnly}> |
| 34 | + {options.map((option) => ( |
| 35 | + <RadioOption key={option.value} name={name} option={option} /> |
| 36 | + ))} |
| 37 | + </AntRadio.Group> |
| 38 | + </AntForm> |
| 39 | + ); |
| 40 | +}; |
| 41 | + |
| 42 | +Radio.propTypes = { |
| 43 | + ...wrapperProps, |
| 44 | + options: PropTypes.arrayOf( |
| 45 | + PropTypes.shape({ |
| 46 | + value: PropTypes.any, |
| 47 | + label: PropTypes.node |
| 48 | + }) |
| 49 | + ), |
| 50 | + label: PropTypes.node.isRequired, |
| 51 | + isDisabled: PropTypes.bool, |
| 52 | + isReadOnly: PropTypes.bool, |
| 53 | + children: PropTypes.any, |
| 54 | + description: PropTypes.node |
| 55 | +}; |
| 56 | + |
| 57 | +Radio.defaultProps = { |
| 58 | + options: [] |
| 59 | +}; |
| 60 | + |
| 61 | +export default Radio; |
0 commit comments