Toshio Blog

formik-material-uiでのCheckboxの初期値

September 28, 2018

material-uiとformikを苦労なくつなぎこみたい場合、以下のモジュールがあります。

https://github.com/stackworx/formik-material-ui

ただ2018/09の時点ではcheckboxの振る舞いで初期値にチェックがつけることができなそうです。

手元では修正しましたのでここに載せておきます。

Before: 2018/09の時点でのソース

// @ts-ignore
import * as React from 'react';
import MuiCheckbox, {
CheckboxProps as MuiCheckboxProps,
} from '@material-ui/core/Checkbox';
import { FieldProps } from 'formik';
import { Omit } from './types';
export interface CheckboxProps
extends FieldProps,
Omit<MuiCheckboxProps, 'form'> {}
const Checkbox: React.ComponentType<CheckboxProps> = ({
field,
form: { isSubmitting },
disabled = false,
...props
}) => (
<MuiCheckbox
disabled={isSubmitting || disabled}
{...props}
{...field}
// TODO: is this the correct way?
value={field.value ? 'checked' : ''}
/>
);
Checkbox.displayName = 'FormikMaterialUICheckbox';
export default Checkbox;
view raw Checkbox.tsx hosted with ❤ by GitHub

After: 修正したファイル

import MuiCheckbox from '@material-ui/core/Checkbox'
const Checkbox = ({
field,
form: { isSubmitting },
disabled = false,
...props
}) => {
return (
<MuiCheckbox
disabled={isSubmitting || disabled}
{...props}
{...field}
checked={field.value == (props.value || "true") ? true : false}
value={props.value || "true"}
/>
)}
export default Checkbox
view raw Checkbox.js hosted with ❤ by GitHub

使用例:

import FormControlLabel from '@material-ui/core/FormControlLabel'
import { Field } from 'formik'
import Checkbox from 'path/to/myCheckbox'
<FormControlLabel
label="ラベル"
control={
<Field
name="anything"
component={Checkbox}
value="1"
/>
}
/>
view raw sample-use.js hosted with ❤ by GitHub

2018/10時点ではいつ取り込まれるのか分かりませんがPRがありますね。

https://github.com/stackworx/formik-material-ui/pull/27/files

const Checkbox: React.ComponentType<CheckboxProps> = ({
field,
form: { isSubmitting },
disabled = false,
LabelProps,
...props
}) => (
<FormControlLabel
control={
<MuiCheckbox
disabled={isSubmitting || disabled}
value={field.name}
checked={field.value}
{...props}
{...field}
/>
}
{...LabelProps}
/>
);
view raw PRCheckbox.tsx hosted with ❤ by GitHub

FormControlLabel が追加されていて、valueに field.nameが設定されていますね。

以下のようにfield.nameの値がPOSTされるような形なのでしょうか。

[
  'someCheckboxFieldName' => 'someCheckboxFieldName'
]

どのような挙動になるか確かではありませんが、面白いですね。

以上です。


Written by Ta Toshio who lives and works in Saitama, Japan .You should follow him on Twitter