Unform

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';
3
4interface Props extends InputHTMLAttributes<HTMLInputElement> {
5 name: string;
6 options: {
7 id: string;
8 value: string;
9 label: string;
10 }[];
11}
12
13const CheckboxInput: React.FC<Props> = ({ name, options, ...rest }) => {
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.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]);
38
39 return (
40 <div>
41 {options.map((option, index) => (
42 <label htmlFor={option.id} key={option.id}>
43 <input
44 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};
59
60export default CheckboxInput;

Usage example

1import React, { useRef } from 'react';
2import { FormHandles } from '@unform/core';
3import { Form } from '@unform/web';
4
5import { CheckboxInput } from '../../components/Form';
6
7interface CheckboxOption {
8 id: string;
9 value: string;
10 label: string;
11}
12
13const CheckboxForm: React.FC = () => {
14 const formRef = useRef<FormHandles>(null);
15
16 const checkboxOptions: CheckboxOption[] = [
17 { id: 'node', value: 'node', label: 'Node' },
18 { id: 'react', value: 'react', label: 'ReactJS' },
19 ];
20
21 function handleSubmit(data) {
22 /**
23 * Out example when 'Node' marked: ['node']
24 * You get a string array with the value
25 */
26 console.log(data);
27 }
28
29 return (
30 <Form
31 ref={formRef}
32 onSubmit={handleSubmit}
33 initialData={{ checkbox: ['node'] }}
34 >
35 <CheckboxInput name="checkbox" options={checkboxOptions} />
36
37 <button type="submit">Enviar</button>
38 </Form>
39 );
40};
41
42export default CheckboxForm;
Edit this page on GitHub