Editable table

Table with an input in every cell, only edited cell rerenders

#NameEmailQty
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
  • EditableTable.tsx
  • RowResetButton.tsx
  • RowsTable.tsx
  • data.ts
  • types.ts
import { Button, Group, Stack } from '@mantine/core';
import { FormErrors, isEmail, isNotEmpty, useForm } from '@mantine/form';
import { notifications } from '@mantine/notifications';
import { ROWS } from './data';
import { RowsTable } from './RowsTable';
import { TableValues } from './types';

export function EditableTable() {
  const form = useForm<TableValues>({
    initialValues: {
      rows: ROWS,
    },
    validate: {
      rows: {
        name: isNotEmpty('Required'),
        email: isEmail('Invalid email'),
        quantity: (value) => (typeof value === 'number' && value >= 0 ? null : 'Must be 0 or more'),
      },
    },
  });

  const dirty = form.useDirty();

  const handleSubmit = (values: TableValues) => {
    const changedRows = values.rows.filter((_, index) => form.isDirty(`rows.${index}`)).length;
    form.setInitialValues(values);
    form.resetDirty(values);
    notifications.show({
      title: 'Changes saved',
      message: `${changedRows} ${changedRows === 1 ? 'row' : 'rows'} changed`,
    });
  };

  const handleErrors = (errors: FormErrors) => {
    form.focusInput(Object.keys(errors)[0]);
  };

  return (
    <form onSubmit={form.onSubmit(handleSubmit, handleErrors)}>
      <Stack>
        <RowsTable form={form} />

        <Group justify="flex-end">
          {dirty && (
            <Button size="md" variant="default" onClick={form.reset}>
              Reset all
            </Button>
          )}

          <Button size="md" type="submit">
            Save changes
          </Button>
        </Group>
      </Stack>
    </form>
  );
}