'Best way for handling dynamic forms in React
In my React app, I have an API that takes templateID as a parameter and returns a list of attributes/elements for that template. Each of them has, among other things, a type (input, datePicker, dropdown...) and by their type I can dynamically render them on my page.
For example, if my API returns:
data=[{type:1,...},{type:9,...},{type:4,...},{type:4,...},{type:4,...}]
then I have to render 1 input, 1 multiselect and 3 dropdowns. But all of this can vary depending on the template. I render them using forms like this:
{tempAtr.map((data) =>
required={data.required=== 1 ? true : false}
disabled={data.read_only === 1 ? true : false}
name={data.name}
component={
data.type=== 1 ?Input:
data.type=== 2 ?Input:
data.type=== 3 ?DatePicker:
data.type=== 4 ?DropDownList:
data.type=== 5 ?TextArea :
data.type=== 6 ?DropDownList:
data.type=== 7 ?DropDownList:
data.type=== 8 ?MultiSelect:
data.type=== 9 ?MultiSelect:
Input}
label={data.name}
/>)}
My question is, what is the best way to handle dynamic inputs/dropdowns/all kinds of elements? Usually, if I have a dropdown, I must have a function that handles it's value, and a useState that always has the current state. But I don't know how to do that in a situation like this where I initially don't have the number of elements that I am rendering.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
