0
votes

I have a react form that is dynamically generated via data from DB. The issue I'm currently trying to solve is how to enable/disable "child" inputs based on the "parent" input (typically a checkbox). My plan was during rendering of the form I would create component state settings (parentClicked1, parentClicked2, etc) based on initialValues that are populated by redux-form. The name of the component state setting would correspond to the parent input name and would be passed to an onClick method. for example:

const renderSettings = ({ fields, meta: { touched, error, submitFailed } }) => (
  <div>
    {fields.map((setting, index) => (
      <Field
        name={`${setting}.value`}
        type={fields.get(index).inputType}
        component={renderField}
        label={fields.get(index).labelText}
        format={(value, name) => {
          return setBoolValue(value)
        }}
        onClick={fields.get(index).isParent ? this.onClick(fields.get(index).settingName) : null}
        disabled={fields.get(index).isChild ? this.state[fields.get(index).parentSettingName] : null}
      />
    ))}
  </div>
);

The onClick would have something simple like:

onClick(e, stateKey){
  this.setState({[stateKey]: e.target.value});
}

The issue is setting the initial value of the component state based on the initialValue populated by redux-form. I tried setting in ComponentDidMount and ComponentDidUpdate but neither appears to get populated. How would I go about doing this?

1
could you share example on codesandbox.io? - peeyush singla
Are you just looking for disabling and enabling values of one field on other? - peeyush singla
@peeyushsingla So this is using the same form that is dynamically generated that you had helped me with in another question. :) I modified it slightly but I'm attempting to disable children inputs associated to a parent. codesandbox.io/s/pm42lmy9lm - user1015196
I think even if it's parent or child ultimately it's all part of the same array of fields. If it's the one array of fields and requirement is to disable or enable one field based on another field it's easily achievable by using Fields component of Redux and doesn't require separate state storage. - peeyush singla
@peeyushsingla appreciate your help. I ended up solving this with a slight change to the object model. Enabling and disabling parent does clear out the values and I have all that working. One thing I did have to do was that the values are all stored as strings and so when dealing with checkbox input I have to convert string to bool. - user1015196

1 Answers

0
votes

Have you looked into the redux-form example of initializing from state? https://redux-form.com/7.4.2/examples/initializefromstate/ If the response from your database is mapped to your field name in the parent, it should populate the correct data in the child.

You can use a formValueSelector from redux form to check if the parent is clicked to populate the child component.