diff --git a/packages/react/lib/RadioField/index.js b/packages/react/lib/RadioField/index.js new file mode 100644 index 000000000..ebfcd3b82 --- /dev/null +++ b/packages/react/lib/RadioField/index.js @@ -0,0 +1,110 @@ +import { forwardRef, useReducer, useRef } from 'react'; +import PropTypes from 'prop-types'; +import { classNames, mockState } from '@junipero/core'; + +const RadioField = forwardRef(({ + className, + disabled = false, + id, + name, + options = [], + value, + parseValue = val => val.value ?? val, + parseTitle = val => val?.title ?? val?.toString?.(), + parseDescription = val => val?.description || '', + onChange = () => {}, + ...rest +}, ref) => { + const inputRefs = useRef([]); + const innerRefs = useRef([]); + const wrapperRef = useRef(); + const [state, dispatch] = useReducer(mockState, { + focused: null, + dirty: false, + value, + valid: false, + }); + + const isChecked = option => + state.value === option || state.value === parseValue(option); + + const onChange_ = option => { + dispatch({ value: option, valid: true, dirty: true }); + onChange({ value: parseValue(option), valid: true }); + }; + + const onKeyDown = (option, e) => { + if ( + state.value !== option && + state.value !== parseValue(option) && + (e.key === 'Enter' || e.key === ' ') + ) { + onChange_(option); + } + + return true; + }; + + return ( +
+ { options.map((option, index) => ( +