Search code examples
javascriptreactjstypescriptformikformik-material-ui

Formik checkbox not working properly with withFormik


I have such code in my Form component which basically renders list of checkboxes based on array coming from props.

{permissions?.map((permissions) => {
                        return (
                            <Styled.FormItem key={permissions.name}>
                                <Field
                                    as={FormControlLabel}
                                    name="permissions"
                                    value={permissions.name}
                                    label={permissions.name}
                                    control={<Checkbox color={'primary'} />}
                                />
                            </Styled.FormItem>
                        );
                    })}

As I understand from Formik documentation sample for checkboxes in this way I get permissions field in values with array of checked values. And this works fine until I want to make some of the fields be prechecked when I open the form. I am using withFormik HOC in such way

const EditRoleFormFormik = withFormik<FormProps, any>({
    mapPropsToValues: ({ role }) => {
        const permissions = role?.permissions.map(({ name }) => {
            return { name };
        });
        return { id: role?.id, name: role?.name, permissions: ['AB_TEST_VIEW'] };
    },
    enableReinitialize: true,
    handleSubmit: (values: Partial<Role>, { props: { onSubmit } }) => {
        onSubmit(values);
    },
})(Form);

My assumption was that by defining permissions field in mapPropsToValues I can make some fields prechecked (since above I hardcoded only AB_TEST_VIEW I expected only this to be prechecked). But this doesn't work. How can I precheck checkboxes using this approach?


Solution

  • You should store the selected permissions in a separate property.

        const permissions = [
            {
                name: "p1",
            },
            {
                name: "p2",
            },
            {
                name: "p3",
            }
        ]
    
        const selectedPermissions = ["p1", "p2"]
    
    

    Set formik initialValues

    initialValues = {
        {
            permissions: permissions,
            selectedPermissions: selectedPermissions
        }
    

    And use permissions to create the checkboxes but name it selectedPermissions

    {permissions?.map((permission) => {
        return (
            <label>
                <Field
                    type="checkbox"
                    name="selectedPermissions"
                    value={permission.name}
                />
                {permission.name}
            </label>
    
    
        )
    })}
    
    

    Hope that helps.