Mantine: how to combine use-form with Select and numbers

Viewed 341

I want to build a form that can be used to manage an option that is stored in the database as a number.

However, if I now enter the item from the database into the hook:

const form = useForm({.
  initialValues: { 
     option: 1
  },
});

Is this not compatible with the Select component, because it works internally only with strings. So in this case the correct value is not selected:

<Select
  label="Option"
  {...form.getInputProps("option")}
/>

Now how can I solve this problem in an elegant way? Is there an API/option for this or do I really need to manually convert each numeric value into a string to make this compatible with Mantine?

Thanks a lot.

1 Answers

I use this code:

import { Select } from "@mantine/core";
import { useForm } from "@mantine/form";

const data = [
    { value: '', label: 'Select' },
    { value: 2, label: 'New' }
];

export default function MyForm() {
    const form = useForm({
        initialValues: {
            status: ''
        },
    });
    return (
        <form onSubmit={form.onSubmit((values) => console.log(values))}>
            <Select label="Status" placeholder="Status"
                data={data}
                {...form.getInputProps('status')} />
            <Group position="right" mt="md">
                <Button type="submit">Submit</Button>
            </Group>
        </form>
    );
}
Related