I have a dynamic form templated this way:
class betClient extends Component(
state = {
.............
}
................
const ServerConfigDetails = this.state.ServerConfigDetail.map(field => {
let SecretFields = "access_token" || "api_token" || "private_token" || "password" || "security_token" || "client_secret" || "refresh_token" || "oauth_client_id" || "oauth_client_secret" || "developer_token"
if (field.name === SecretFields) {
return <SecretInput inputlabel = {
field.name == SecretFields ? field.name : null
}
placeholder = {
field.placeholder
}
/>
}
if (field.name === "start_date") {
return <SelectDateInput inputlabel = "Start Date" / >
}
if (field.name === "end_date") {
return <SelectDateInput inputlabel = "End Date" / >
}
// Here we template all other fields that aren't date or secret field
if (field.name !== SecretFields) {
return <TextInputs inputlabel = {
field.label == null ? field.name : field.label
}
placeholder = {
field.placeholder
}
/>
}
})
render() {
return (
<div>
<Modal>
<form>
{ServerConfigDetails}
</form>
</Modal>
</div>
)
}
)
Everything works fine, the form is rendered dynamically but I somehow don't know how to get the form inputs preferably as an object into a state without having to declare each field individually in the initial state. Any help with this?
Not sure if this is clear enough but I will gladly provide any extra information.
I would first suggest, we should decide how our state might look like -
Then make all your components - controlled - you control what to set by passing a value prop (and finally passing to your native inputs)
And finally add onChange handlers for both your select and dynamic input field components. (and finally passing to your native inputs)
These handlers will handle state such that keys are added if not present with value from the event target; add replace (overwrite) current key-value if a new value is entered.
This one is way to go about it.