Unform
Radio
Radio
⚠️ All examples below are using TypeScript, if you're not using it you can simply remove all type definitions as the
React.FC<Props>
from 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';34interface Props extends InputHTMLAttributes<HTMLInputElement> {5 name: string;6 options: {7 id: string;8 value: string;9 label: string;10 }[];11}1213const RadioInput: React.FC<Props> = ({ name, options, ...rest }) => {14 const inputRefs = useRef<HTMLInputElement[]>([]);15 const { fieldName, registerField, defaultValue = '' } = useField(name);1617 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]);3435 return (36 <>37 {options.map(option => (38 <label htmlFor={option.id} key={option.id}>39 <input40 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};5455export default RadioInput;
Usage example
1const App: React.FC = () => {2 const radioOptions = [3 { id: 'rocketseat', value: 'rocketseat', label: 'Rocketseat' },4 { id: 'eliasgcf', value: 'eliasgcf', label: 'EliasGcf' },5 ];67 function handleSubmit(data) {8 /**9 * Out example when 'EliasGcf' marked: { user: 'eliasgcf' }10 * You get a string with the value11 */12 console.log(data);13 }1415 return (16 <Form onSubmit={handleSubmit} initialData={{ radio: radioOptions[1].id }}>17 <RadioInput name="user" options={radioOptions} />1819 <button type="submit">Open</button>20 </Form>21 );22};2324export default App;