In ReactJs, How to dynamically change the Input type from "text" to "select"?

I have following code

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

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?

3 answers

  • answered 2021-09-27 16:22 Leonardo Fachini Martins

    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.

  • answered 2021-09-27 16:33 warheat1990

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

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

  • answered 2021-09-27 17:00 Bojan Tomić

    This is not a good way to do this. It's not readable code and honestly I am not sure how it would render or hydrate.Looks to me like a bug waiting to happen. This is a use case for conditional rendering.

    const myInput = type === "fixed" ? <Input type="select"> : <Input type="text">

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum