0

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?

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.