Select all checkbox
Select all checkbox with indeterminate state for a checkbox group
import { Button, Checkbox, Group, Stack, TextInput } from '@mantine/core';
import { FormErrors, isNotEmpty, useForm } from '@mantine/form';
import { notifications } from '@mantine/notifications';
import { permissions } from './data';
interface RoleValues {
name: string;
permissions: string[];
}
export function SelectAll() {
const form = useForm<RoleValues>({
initialValues: {
name: '',
permissions: ['read'],
},
validate: {
name: isNotEmpty('Role name is required'),
permissions: (value) => (value.length === 0 ? 'Select at least one permission' : null),
},
});
const selected = form.useWatchValue('permissions');
const allSelected = selected.length === permissions.length;
const indeterminate = selected.length > 0 && !allSelected;
const items = permissions.map((item) => (
<Checkbox
key={item.value}
value={item.value}
label={item.label}
description={item.description}
ml={30}
/>
));
const handleSubmit = (values: RoleValues) => {
notifications.show({
title: 'Role created',
message: `Role ${values.name} created with ${values.permissions.length} ${values.permissions.length === 1 ? 'permission' : 'permissions'}`,
});
};
const handleErrors = (errors: FormErrors) => {
form.focusInput(Object.keys(errors)[0]);
};
return (
<form onSubmit={form.onSubmit(handleSubmit, handleErrors)}>
<Stack>
<TextInput
size="md"
label="Role name"
placeholder="Maintainer"
withAsterisk
{...form.getInputProps('name')}
/>
<div>
<Checkbox
size="md"
label="Permissions"
fw={500}
checked={allSelected}
indeterminate={indeterminate}
onChange={() =>
form.setFieldValue(
'permissions',
allSelected ? [] : permissions.map((item) => item.value)
)
}
/>
<Checkbox.Group
size="md"
errorProps={{ mt: 'xs' }}
{...form.getInputProps('permissions')}
>
<Stack gap="sm" mt="sm">
{items}
</Stack>
</Checkbox.Group>
</div>
<Group justify="flex-end">
<Button size="md" variant="default" onClick={form.reset}>
Reset
</Button>
<Button size="md" type="submit">
Create role
</Button>
</Group>
</Stack>
</form>
);
}