davidkpiano / react-redux-form

Create forms easily in React with Redux.
https://davidkpiano.github.io/react-redux-form
MIT License
2.07k stars 251 forks source link

How to conditionally render parts of form based on other Fields #1191

Closed adrienshen closed 5 years ago

adrienshen commented 5 years ago

The Problem

I would like to render or not render certain parts of the form based on early parts of the form. For example I have the fields: payment_type["cash", "insurance"] If insurance is selected, I would like to render certain insurance specific fields. And if cash is selected, I would like to render other fields. As it is, I see the the values are attached to the component and not easily accessibly at the parent level of redux forms. Is there currently a straight forward way I can accomplish this tasks?

Reproducible Code Example

(please fork from this CodePen template or this CodeSandbox template)

      <section id="registration">
        <Field
          name="registration_cost"
          label="Registration fees"
          component={renderSelectList}
          data={[
            {
              display: "Insurance",
              value: "I",
            },
            {
              display: "Cash",
              value: "C",
            },
            {
              display: "Exemption",
              value: "E",
            }
          ]}
        />
      </section>
      <section id="Fingerprint">
        <Button>Enroll Fingerprint</Button>
      </section>
      <section>
        <Field
          name="patient_type"
          label="Patient type"
          component={renderSelectList}
          data={[
            {
              display: "In-Patient",
              value: "I",
            },
            {
              display: "Out-Patient",
              value: "O",
            }
          ]} />
      </section>
      <section>
        <Field
          name="consultation"
          label="Consultation"
          component={renderOptionSelect}
          data={ConsultationType} />
      </section>
      <section>
        <Field
          name="consultation"
          label="Consultation"
          component={renderOptionSelect}
          data={["Yes", "No"]} />
      </section>
      <section>
        <Price>300.00</Price>
        <Button
          htmlType="submit"
          type="primary"
          disabled={pristine || submitting}>
          Submit
        </Button>
      </section>
rikkit commented 5 years ago

If you're using Form, the form state is in your redux store so you can just bind to the value of the field. If you're using LocalForm, you'll need to use the onChange handler to store the form data in a local component where you can access it. It's not clear from your example code which you're using so it's difficult to help more.

adrienshen commented 5 years ago

Oh, I am use Form, however I resolve this already. Thanks closing now.