CheckboxField.js 879 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import React from 'react';
  2. import { at } from 'lodash';
  3. import { useField } from 'formik';
  4. import {
  5. Checkbox,
  6. FormControl,
  7. FormControlLabel,
  8. FormHelperText
  9. } from '@material-ui/core';
  10. export default function CheckboxField(props) {
  11. const { label, ...rest } = props;
  12. const [field, meta, helper] = useField(props);
  13. const { setValue } = helper;
  14. function _renderHelperText() {
  15. const [touched, error] = at(meta, 'touched', 'error');
  16. if (touched && error) {
  17. return <FormHelperText>{error}</FormHelperText>;
  18. }
  19. }
  20. function _onChange(e) {
  21. setValue(e.target.checked);
  22. }
  23. return (
  24. <FormControl {...rest}>
  25. <FormControlLabel
  26. value={field.checked}
  27. checked={field.checked}
  28. control={<Checkbox {...field} onChange={_onChange} />}
  29. label={label}
  30. />
  31. {_renderHelperText()}
  32. </FormControl>
  33. );
  34. }