Unform

Radio

Radio

⚠️ All examples below are using TypeScript. If you're not using it, you can remove all type definitions from the component definition.

Click here to access a Radio Input Live Demo.

Radio input component

1import React, { useEffect, useRef, InputHTMLAttributes } from 'react';
2import { useField } from '@unform/core';
3
4interface Props extends InputHTMLAttributes<HTMLInputElement> {
5 name: string;
6 options: {
7 id: string;
8 value: string;
9 label: string;
10 }[];
11}
12
13export default function RadioInput({ name, options, ...rest }: Props) {
14 const inputRefs = useRef<HTMLInputElement[]>([]);
15 const { fieldName, registerField, defaultValue = '' } = useField(name);
16
17 useEffect(() => {
18 registerField({
19 name: fieldName,
20 ref: inputRefs.current,
21 getValue: (refs: HTMLInputElement[]) => {
22 return refs.find(ref => ref.checked)?.value || '';
23 },
24 setValue: (refs: HTMLInputElement[], id: string) => {
25 const inputRef = refs.find(ref => ref.id === id);
26 if (inputRef) inputRef.checked = true;
27 },
28 clearValue: (refs: HTMLInputElement[]) => {
29 const inputRef = refs.find(ref => ref.checked === true);
30 if (inputRef) inputRef.checked = false;
31 },
32 });
33 }, [defaultValue, fieldName, registerField]);
34
35 return (
36 <>
37 {options.map(option => (
38 <label htmlFor={option.id} key={option.id}>
39 <input
40 ref={ref => inputRefs.current.push(ref as HTMLInputElement)}
41 id={option.id}
42 type="radio"
43 name={name}
44 defaultChecked={defaultValue.includes(option.id)}
45 value={option.value}
46 {...rest}
47 />
48 {option.label}
49 </label>
50 ))}
51 </>
52 );
53};

Usage example

1export default function App() {
2 const radioOptions = [
3 { id: 'rocketseat', value: 'rocketseat', label: 'Rocketseat' },
4 { id: 'eliasgcf', value: 'eliasgcf', label: 'EliasGcf' },
5 ];
6
7 function handleSubmit(data) {
8 /**
9 * Out example when 'EliasGcf' marked: { user: 'eliasgcf' }
10 * You get a string with the value
11 */
12 console.log(data);
13 }
14
15 return (
16 <Form onSubmit={handleSubmit} initialData={{ radio: radioOptions[1].id }}>
17 <RadioInput name="user" options={radioOptions} />
18
19 <button type="submit">Open</button>
20 </Form>
21 );
22};
Edit this page on GitHub