State management in React Dynamic from JSON

172 Views Asked by At

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.

1

There are 1 best solutions below

0
On

I would first suggest, we should decide how our state might look like -

{
selects: {
 // With individual keys with default values
},
dynamic: {} // no key-value pairs at first
}

Then make all your components - controlled - you control what to set by passing a value prop (and finally passing to your native inputs)


const { selects, dynamic } = this.state;

// pass a value prop as selects.<key-name> or empty string

And finally add onChange handlers for both your select and dynamic input field components. (and finally passing to your native inputs)

onChangeSelectField (event, fieldName) {}
//Same for InputField

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.

{
    const currentDynamicData = this.state.dynamic;
    const newData = { ... currentDynamicData, {... updatedData}}; // updatedData is newer key-value pair

this.setState({ dynamic: newData });
}

This one is way to go about it.