I am trying to make a form builder which takes fields and form (from useForm) to simply map over the fields array and return input based on the type of field, and register the field to mantine form like {...form.getInputProps(name)} where form if the props send to FormBuilderComponent. But doing so I am unable to interact with the input fields. Please help me. here's the link to codesandbox. https://codesandbox.io/s/awesome-almeida-58e4nc?file=/src/App.tsx What am I missing?
const FormBuilder = ({ fields, form }) => {
const theme = useMantineTheme();
console.log(form);
const mappedFields = fields.map((field) => {
const {
type,
placeholder,
name,
label,
options,
col,
pattern,
required,
errorMessage,
minLength,
maxLength
} = field;
if (type === "select") {
return (
<Select
transition="pop-bottom-left"
transitionDuration={80}
transitionTimingFunction="ease"
label={label}
data={options}
placeholder={placeholder}
required={required}
/>
);
}
if (type === "text") {
return (
<Grid.Col {...form.getInputProps(name)} span={col} key={randomId()}>
<TextInput
placeholder={placeholder}
label={label}
// required={required}
{...form.getInputProps(name)}
/>
</Grid.Col>
);
}
if (type === "date-picker") {
return (
<Grid.Col span={col} {...form.getInputProps(name)} key={randomId()}>
<DatePicker
placeholder={placeholder}
label={label}
withAsterisk={required}
// {...form.getInputProps(name)}
/>
</Grid.Col>
);
}
if (type === "switch") {
return (
<Grid.Col span={col} key={randomId()}>
<Switch
color="teal"
size="md"
label={label}
// required={required}
// checked
thumbIcon={
true === true ? (
<IconCheck
size={12}
color={theme.colors.teal[theme.fn.primaryShade()]}
stroke={3}
/>
) : (
<IconX
size={12}
color={theme.colors.red[theme.fn.primaryShade()]}
stroke={3}
/>
)
}
/>
</Grid.Col>
);
}
if (type === "number") {
return (
<Grid.Col span={col} key={randomId()}>
<NumberInput
placeholder={placeholder}
label={label}
withAsterisk={required}
// minLength={minLength}
// maxLength={maxLength}
/>
</Grid.Col>
);
}
});
return <>{mappedFields}</>;
};
export default function App() {
const form = useForm();
return (
<MantineProvider withGlobalStyles withNormalizeCSS>
<form>
<Grid>
<FormBuilder fields={fields} form={form} />
<Grid.Col span={12}>
<Input placeholder='hy' {...form.getInputProps('ghost')} />
</Grid.Col>
<Grid.Col span={12}>
<Group position='right' mt={'md'}>
<Button type={'submit'}>Next</Button>
</Group>
</Grid.Col>
</Grid>
</form>
</MantineProvider>
);
}
I want to build a form with multiple input fields and want to read it's value and validate them from the parent component.