1

I am trying to build a form based on Redux Form - Wizard Example (https://codesandbox.io/s/0Qzz3843). On the first page of the questionnaire, I have a set of options (checkbox). I want to be able to generate the succeeding pages based on what the user selected on the first page. If, for example, the user selected options A,B and F from options A-J, the succeeding pages will only be questions for A, B and F, respectively. These succeeding pages will have the same set of fields (title, description, budget).

I am sure I only need to create one component for this set of fields, plus another component/s that I need to be able to dynamically produce the pages for each state (option) set in the first page.

I am thinking a switch/case without a break for each case might work (implemented inside my wrapper component), but would there be a more elegant way of doing it?

I am very new to this and would greatly appreciate directions/suggestions/help with some codes. Thanks a lot!

1 Answer 1

0

I had to use formValueSelector API to access form values on different pages and then conditional render to show the different pages.

Here is the modified wizard code from the redux-form example Wizard. If you choose male on second page, you get favorite color dropdown question on third page. If you choose female, you get an employed checkbox question.

I made a conditional variable of isMale and return different Field depending on if male answer is true or not. I'm sure there are more elegant ways to do this, but this is one way that worked for me.

https://codesandbox.io/s/34jp9rqp71

I just modified/added these parts of the code.

WizardFormThirdPage.js

import { Field, reduxForm, formValueSelector } from "redux-form";
import { connect } from "react-redux";

let WizardFormThirdPage = props => {
  const { sex, handleSubmit, pristine, previousPage, submitting } = props;
  var isMale = sex == "male" ? true : false;

  return (
    <form onSubmit={handleSubmit}>
      {isMale && (
        <div>
          <label>Favorite Color</label>
          <Field name="favoriteColor" component={renderColorSelector} />
        </div>
      )}
      {!isMale && (
        <div>
          <label htmlFor="employed">Employed</label>
          <div>
            <Field
              name="employed"
              id="employed"
              component="input"
              type="checkbox"
            />
          </div>
        </div>
      )}
      . . .
    </form>
  );
};

const mapStateToProps = state => ({
  sex: formValueSelector("wizard")(state, "sex")
});
WizardFormThirdPage = connect(mapStateToProps)(WizardFormThirdPage);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.