Unform
Checkbox
Checkbox
⚠️ 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.
Checkbox 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 CheckboxInput: 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.filter(ref => ref.checked).map(ref => ref.value);23 },24 clearValue: (refs: HTMLInputElement[]) => {25 refs.forEach(ref => {26 ref.checked = false;27 });28 },29 setValue: (refs: HTMLInputElement[], values: string[]) => {30 refs.forEach(ref => {31 if (values.includes(ref.id)) {32 ref.checked = true;33 }34 });35 },36 });37 }, [defaultValue, fieldName, registerField]);3839 return (40 <div>41 {options.map((option, index) => (42 <label htmlFor={option.id} key={option.id}>43 <input44 defaultChecked={defaultValue.find((dv: string) => dv === option.id)}45 ref={ref => {46 inputRefs.current[index] = ref as HTMLInputElement;47 }}48 value={option.value}49 type="checkbox"50 id={option.id}51 {...rest}52 />53 {option.label}54 </label>55 ))}56 </div>57 );58};5960export default CheckboxInput;
Usage example
1import React, { useRef } from 'react';2import { FormHandles } from '@unform/core';3import { Form } from '@unform/web';45import { CheckboxInput } from '../../components/Form';67interface CheckboxOption {8 id: string;9 value: string;10 label: string;11}1213const CheckboxForm: React.FC = () => {14 const formRef = useRef<FormHandles>(null);1516 const checkboxOptions: CheckboxOption[] = [17 { id: 'node', value: 'node', label: 'Node' },18 { id: 'react', value: 'react', label: 'ReactJS' },19 ];2021 function handleSubmit(data) {22 /**23 * Out example when 'Node' marked: ['node']24 * You get a string array with the value25 */26 console.log(data);27 }2829 return (30 <Form31 ref={formRef}32 onSubmit={handleSubmit}33 initialData={{ checkbox: ['node'] }}34 >35 <CheckboxInput name="checkbox" options={checkboxOptions} />3637 <button type="submit">Enviar</button>38 </Form>39 );40};4142export default CheckboxForm;