javascriptreactjsformsreact-final-form

React Final Form - Double conditional Form


I have started to work on a form project using React final form, but I am struggling to do a two condition question.

Would anyone knows how to do a double conditional logic on React final form. From this example, the single conditional logic code is given :

const Condition = ({ when, is, children }) => ( <Field name={when} subscription={{ value: true }}>
{({ input: { value } }) => (value === is ? children : null)}  </Field>)

However, I don't know how to do a double conditional one that would require 2 different answers from two different questions in the form to be checked before displaying the conditional question.

Thank you :)


Solution

  • You could use useFormState from react-final-form to obtain current form state, so MultiCondition component could look like this:

    const MultiCondition = ({ condition, children }) => {
      const { values = {} } = useFormState({ subscription: { values: true } });
      return condition(values) ? children : null;
    };
    

    than somewhere inside the form:

    <MultiCondition condition={({ gift, firstName }) => gift && firstName === "Joe"}>
      <span>gets rendered when condition is satisfied</span>
    </MultiCondition>