Home > Back-end >  In ReactJs, How to dynamically change the Input type from "text" to "select"?
In ReactJs, How to dynamically change the Input type from "text" to "select"?

Time:09-28

I have following code

                 <Controller
                  control={control}
                  name='part'
                  render={({ field }) => (
                    <Input
                      type={(type === "fixed") ? "select" : "text"}
                      name="part"
                      className={errors.part && "is-invalid"}
                      value={field.value || ""}
                      onChange={(value) => field.onChange(value)}
                    >
                      //this code is causing error
                      {(type === "fixed") &&
                        partnOptions.map((opt) =>
                          <option value={opt.code} key={opt.code}>{opt.code}</option>
                        )
                      }
                    </Input>
                  )}
                />

And I got an error input is a void element tag and must neither have children nor use dangerouslySetInnerHTML which is understandable because I guess type text should not have any children. If I remove the map part it's working correctly, the Input field will change from text to select based on the type value. So, how do I include the option when the Input type is changed to select?

CodePudding user response:

In deed <Input> is a void element! You shouldn't add anything inside of it. Also, there isn't an input of type == "select". input types documentation

I would strongly suggest you to switch the conditional rendering to either render <input type="text" /> or <select> elements Select with option documentation.

CodePudding user response:

I forgot to mention that I'm using reactstrap, so type='select' is valid. I managed to achieve this by adding : undefined

                      {(type === "fixed") ?
                        partOptions.map((opt) =>
                          <option value={opt.code} key={opt.code}>{opt.code}</option>
                        ) : undefined
                      }
  • Related