Search code examples
javascriptreactjsreduxreact-final-form

React final form disables fields without redux


I have the following functions which renders a set of fields:

const renderFields = (data: CustomerDetails) => {
  return Object.keys(data).map((s: string) => {
    const key = s as keyof CustomerDetails

    return Object.keys(data[key]).map(fieldKey => {
      const name = `${key}.${fieldKey}`
      const id = `customer-details-form-${fieldKey}`

      return (
        <FormItem key={name}>
          <Label htmlFor={id}>{camelCaseToTitleCase(fieldKey)}</Label>
          <Field name={`${key}.${fieldKey}.value`} validate={validate(fieldKey)}>
            {props => 
              <TextField
                disabled={
                  data.contact[fieldKey] !== undefined 
                  ? data.contact[fieldKey].disabled
                  : true
                }
                // disabled={
                //   data.contact[fieldKey]?.disabled ?? true
                // }
                {...props}
                data-bdd={`customer_details_field_${fieldKey}`}
                id={id}
              />
            }
          </Field>
        </FormItem>
      )
    })
  })
}

however the disabled status is dependent on the redux structure at the moment. Is there a way to make fields disabled/enabled on click without having to dispatch an action saying which fields should be enabled or not?


Solution

  • Using local state here would be appropriate. Here's a simplified example:

    function WrappedField(props){
      const [disabled, setDisabled] = useState(false);
      return <Field {...props} disabled={disabled} onClick={() => setDisabled(!disabled)} />
    }
    

    You can use the wrapped version wherever you would have used the Field component.