Back to all questions

Can I use an array of strings as a list in use-form?

Last updated

What is use-form list?

use-form supports nested values in array format. There are handlers available to add, remove, and reorder items in the list:

  • form.removeListItem – removes list item at given index
  • form.insertListItem – inserts list item at given index (appends item to the end of the list if index is not specified)
  • form.reorderListItem – reorders list item with given position at specified field

Example of using form lists:

import { IconTrash } from '@tabler/icons-react';
import {
  ActionIcon,
  Box,
  Button,
  Group,
  Switch,
  Text,
  TextInput,
} from '@mantine/core';
import { useForm } from '@mantine/form';
import { randomId } from '@mantine/hooks';

function Demo() {
  const form = useForm({
    mode: 'uncontrolled',
    initialValues: {
      employees: [{ name: '', active: false, key: randomId() }],
    },
  });

  const fields = form.getValues().employees.map((item, index) => (
    <Group key={item.key} mt="xs">
      <TextInput
        placeholder="John Doe"
        withAsterisk
        style={{ flex: 1 }}
        key={form.key(`employees.${index}.name`)}
        {...form.getInputProps(`employees.${index}.name`)}
      />
      <Switch
        label="Active"
        key={form.key(`employees.${index}.active`)}
        {...form.getInputProps(`employees.${index}.active`, {
          type: 'checkbox',
        })}
      />
      <ActionIcon
        color="red"
        onClick={() => form.removeListItem('employees', index)}
      >
        <IconTrash size="1rem" />
      </ActionIcon>
    </Group>
  ));

  return (
    <Box maw={500} mx="auto">
      {fields.length > 0 ? (
        <Group mb="xs">
          <Text fw={500} size="sm" style={{ flex: 1 }}>
            Name
          </Text>
          <Text fw={500} size="sm" pr={90}>
            Status
          </Text>
        </Group>
      ) : (
        <Text c="dimmed" ta="center">
          No one here...
        </Text>
      )}

      {fields}

      <Group justify="center" mt="md">
        <Button
          onClick={() =>
            form.insertListItem('employees', {
              name: '',
              active: false,
              key: randomId(),
            })
          }
        >
          Add employee
        </Button>
      </Group>
    </Box>
  );
}

Form lists limitation

use-form lists are designed to work with objects, any other values are not supported. This limitation is implemented on purpose to avoid confusing form lists with arrays of other types of values.