Reputation: 193
I am dealing with how to generate a JSX element inside return of a React component using map. I am trying to make a dynamic form and the source is a given array:
I have two types of forms and the key "tipo" is the condition
Array with data:
let data = [
{ tipo: "input",
label: "label1",
name: "name1",
placeholder: "placeholder1",
defaultValue: "defaulvalue1",
},
{ tipo: "datepiker",
label: "label2",
name: "name2",
placeholder: "placeholder2",
defaultValue: "defaulvalue2",
},
];
The default normal code is: ( form type: input).
<FormItem label="labe1">
<Input name="name1" placeholder="placeholder1" defaultValue=defaultvalue1 />
</FormItem>
In case we have a condition datepike we just replace with:
<DatePicker name="name" defaultValue={moment("defaultvalue1")} />
Esto es un intento incompleto:
<div>
{data.map((value) => (
<Fragment>
<FormItem label={value.label}>
*** condition *** if input or datepike
</FormItem>
</Fragment>
))}
</div>
Any idea on how to acomplish this?
Upvotes: 0
Views: 192
Reputation: 11011
You can add the &&
condition on tipo
and render accordingly.
<div>
{data.map(({ label, tipo, name, defaultValue, placeholder }) => (
<Fragment>
<FormItem label={label}>
{tipo === "input" && (
<Input
name={name}
placeholder={placeholder}
defaultValue={defaultvalue}
/>
)}
{tipo === "datepiker" && (
<DatePicker name={name} defaultValue={moment(defaultValue)} />
)}
</FormItem>
</Fragment>
))}
</div>
Upvotes: 0
Reputation: 1449
You can use a tenary operation:
<div>
{data.map((value) => (
<Fragment>
<FormItem label={value.label}>
{value.tipo === "input" ? <Input name="name1" /> : <DatePicker name="name"/>}
</FormItem>
</Fragment>
))}
</div>
Upvotes: 2