This repository was archived by the owner on Apr 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 468
Expand file tree
/
Copy pathradio.tsx
More file actions
103 lines (86 loc) · 2.49 KB
/
radio.tsx
File metadata and controls
103 lines (86 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import { useEffect, useRef, InputHTMLAttributes, RefObject } from 'react'
import { useField, SubmitHandler, FormHandles } from '@unform/core'
import { Form } from '@unform/web'
/**
* This is a Radio component that supports rendering multiple options.
*
* https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio
*/
interface Props {
name: string
label?: string
options: {
id: string
value: string
label: string
}[]
}
type RefInputEl = RefObject<HTMLInputElement[]>
type InputProps = InputHTMLAttributes<HTMLInputElement> & Props
function Radio({ name, label, options, ...rest }: InputProps) {
const inputRefs = useRef([])
const { fieldName, registerField, defaultValue = '', error } = useField(name)
useEffect(() => {
registerField({
name: fieldName,
ref: inputRefs,
getValue: (refs: RefInputEl) => {
return refs.current.find(input => input?.checked)?.value
},
setValue: (refs: RefInputEl, id: string) => {
const inputRef = refs.current.find(ref => ref.id === id)
if (inputRef) inputRef.checked = true
},
clearValue: (refs: RefInputEl) => {
const inputRef = refs.current.find(ref => ref.checked === true)
if (inputRef) inputRef.checked = false
},
})
}, [fieldName, registerField])
return (
<div>
{label && <p>{label}</p>}
{options.map((option, index) => (
<span key={option.id}>
<input
type="radio"
ref={ref => {
inputRefs.current[index] = ref
}}
id={option.id}
name={name}
defaultChecked={defaultValue.includes(option.id)}
value={option.value}
{...rest}
/>
<label htmlFor={option.id} key={option.id}>
{option.label}
</label>
</span>
))}
{error && <span>{error}</span>}
</div>
)
}
/**
* Usage
*/
interface FormData {
username: string
}
export default function App() {
const formRef = useRef<FormHandles>(null)
const handleSubmit: SubmitHandler<FormData> = data => {
console.log(data)
}
const radioOptions = [
{ id: 'jpedroschmitz', value: 'jpedroschmitz', label: 'jpedroschmitz' },
{ id: 'rocketseat', value: 'rocketseat', label: 'Rocketseat' },
]
return (
<Form ref={formRef} onSubmit={handleSubmit}>
<Radio name="username" label="Choose a username" options={radioOptions} />
<button type="submit">Submit</button>
</Form>
)
}