Skip to content

Instantly share code, notes, and snippets.

@dougg0k
Last active June 1, 2020 15:07
Show Gist options
  • Save dougg0k/b616d84c286edfeb6ec46346041fbedc to your computer and use it in GitHub Desktop.
Save dougg0k/b616d84c286edfeb6ec46346041fbedc to your computer and use it in GitHub Desktop.
Unform ReactJS Radio
function App() {
return (
<RadioButton
name="type"
options={OPTIONS}
defaultValue={"Initial Value"}
isLoading={!!"Initial Value already loaded"}
/>
)
}
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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment