|
import { useField } from "@unform/core"; |
|
import React, { InputHTMLAttributes, useRef } from "react"; |
|
import styled from "styled-components"; |
|
import ErrorMessage from "./ErrorMessage"; |
|
import Label from "./Label"; |
|
|
|
const RadioContainer = styled.div` |
|
display: flex; |
|
flex-direction: row; |
|
margin-right: 20px; |
|
align-items: center; |
|
`; |
|
|
|
const RadioGroup = styled.div` |
|
display: flex; |
|
flex-direction: row; |
|
margin-bottom: 5px; |
|
`; |
|
|
|
const Container = styled.div` |
|
display: flex; |
|
flex-direction: column; |
|
`; |
|
|
|
const Radio = styled.input` |
|
margin-right: 5px; |
|
`; |
|
|
|
interface Option { |
|
value: string; |
|
label: string; |
|
} |
|
|
|
interface Props extends InputHTMLAttributes<HTMLInputElement> { |
|
name: string; |
|
options: Array<Option>; |
|
isLoading: boolean; |
|
} |
|
|
|
function RadioButton({ |
|
name, |
|
options, |
|
defaultValue, |
|
isLoading, |
|
...rest |
|
}: Props) { |
|
const refs = useRef<Array<HTMLInputElement>>([]); |
|
const { fieldName, registerField, error } = useField(name); |
|
|
|
registerField({ |
|
name: fieldName, |
|
ref: refs.current, |
|
getValue: (ref) => { |
|
if (!ref || ref.length < 1) { |
|
return ""; |
|
} |
|
const item = ref?.find((item: any) => item.checked); |
|
if (!item) { |
|
return ""; |
|
} |
|
return item?.value; |
|
}, |
|
clearValue: (ref: any) => { |
|
ref.forEach((item: any) => (item.checked = false)); |
|
}, |
|
}); |
|
|
|
function addRefItem(ref: any) { |
|
if (!!ref && !refs.current.includes(ref)) { |
|
refs.current.push(ref); |
|
} |
|
} |
|
|
|
return isLoading ? null : ( |
|
<Container> |
|
<RadioGroup> |
|
{options.map((option, index) => { |
|
const checkboxId = `${fieldName}-${option.value}`; |
|
const isChecked = defaultValue === option.value; |
|
return ( |
|
<RadioContainer key={checkboxId}> |
|
<Radio |
|
{...rest} |
|
type="radio" |
|
id={checkboxId} |
|
name={fieldName} |
|
aria-label={checkboxId} |
|
defaultChecked={isChecked} |
|
value={option.value} |
|
ref={addRefItem} |
|
/> |
|
{!!option.label && <Label>{option.label}</Label>} |
|
</RadioContainer> |
|
); |
|
})} |
|
</RadioGroup> |
|
{!!error && <ErrorMessage>{error}</ErrorMessage>} |
|
</Container> |
|
); |
|
} |
|
|
|
export default RadioButton; |