I am new to React, so I am sorry if this is very rudimentary. I haven’t found a solution online for this exact problem before coming here.
Say I have to create a form with multiple input fields in a row, and I am using a .map() method over a data array to render these fields.
Something like this:
const inputData = [{label: "Name", placeholder: "Name"}, .....]
…More code…
<div> {inputData.map((data) => <UserInput label={data.label} placeholder={data.placeholder} />) </div>
However, the problem I am having is there should be other field types interspersed throughout the form, so that I cannot map through all of the inputData array without putting other fields at the end like a drop-down list, date picker, input fields with left and/or right add-ons, etc. Is calling the UserInput Component in the parent Component for each individual occurrence of an input the best method to go about this, even if there are many? Or is there a way I can still loop over the data and still have other fields in between the input fields, perhaps a different method altogether?
3
Answers
Since
UserInput
is a custom component, you could also give it another parameter liketype
.Obviously your
data
object would need thetype
aswell.If I understand your question correctly, you have an array
inputData
which represents a series of inputs you’d like to include in your form, and you want those represented as<UserInput />
components; but you also have other input types you’d like to include as you see fit (radios, date pickers, etc).First, I suggest trying arellak’s answer, as this may solve your problem, assuming you can handle all of the inputs as
<UserInput />
components.However,
In my opinion, it is odd to represent your
<UserInput />
components as an array, especially if you have a fixed number of inputs. Instead of iterating over your array and renderingUserInput
s, it is much better to hardcode them into the form component’sreturn
orrender
:This has two advantages.
On the other hand, it’s possible that you have a dynamic number of form elements (perhaps you’re receiving
inputData
as a prop from a parent component).If that’s the case, then I suggest you pass in your input components as children. Each time you create a form element, you pass in the inputs as child components.
Parent component:
Form component:
Either way, I suggest you avoid using this array data structure unless you absolutely need to — there are better, more readable ways to do it.
a library can help a lot with complex forms, the most popular seem to be:
https://github.com/react-hook-form/react-hook-form
or
https://formik.org/docs/examples/basic
personally I think formly is the best tool for forms about, but the react version seems unmaintained for a long time and probably doesn’t work with hooks https://github.com/formly-js/react-formly (hope someone proves me wrong tho)