I am building a form using an array of objects that describe the elements within the form.
const fields = [
{ name: "Name", type: "text", placeholder: "What's your fullname?" },
{ name: "Email", type: "email", placeholder: "We promise not to spam you." },
{ name: "Password", type: "password", placeholder: "Make it a good one!" },
{ name: "About", type: "textarea", placeholder: "Tell us a little about yourself ..." },
];
I map over each object to produce my form which all works as desired.
{fields.map((field, index) => (
<div key={form-field-${index}`}>
<label htmlFor={field.name}>{field.name}</label>
<div>
{field.type !== "textarea" &&
<input
type={field.type}
id={field.name}
name={field.name}
placeholder={field.placeholder}
/>
}
{field.type === "textarea" &&
<textarea
id={field.name}
name={field.name}
placeholder={field.placeholder}
/>
}
</div>
</div>
))}
As you can see I have some conditional rendering based on the type value of each field. For two different form elements this is not horrendous, but if I go adding other form elements (<select> for example), I would prefer to not have x conditionals if there is a better alternative.
Is there a better alternative? Move this to its a function, or its own component perhaps?
I am kind of hoping there is a means of doing something like:
{fields.map((field, index) => {
<field.formType
id="{field.name}"
...
/>
});
Where field.formType maps to a formType: "input" in the fields array.
input typeand a value ofcomponent functionwould my go-to