reactjsantd

antd v4 - Steps and Form


I am new to React and i am playing around with ant design. I need to build a multi-step form where each step has a couple of fields and the final step will have a submit button. This would use useForm hook from antd. I would prefer not to use any other plugins like antd-form-builder etc.

The issue i am facing is that in the multi-step form, at the last step, when i press submit the form data for last step is available and data for previous steps is not available. I reckon this could be because the step is being replaced in DOM when i move to "next" step.

Is there any simpler way to obtain the data from all forms at the last step ?

I have prepared a codesandbox for the sample.. Refer the console after submitting.

https://codesandbox.io/s/cool-mcnulty-or8jw

Thanks for the help!


Solution

  • Yes it's because your steps are destroyed when you're not showing them in the DOM.

    Add a step to your steps array like this:

    const steps = [
        {
          step: 1,
          title: "Step1",
          content: <Step1Form />
        },
        {
          step: 2,
          title: "Step2",
          content: <Step2Form />
        }
    ];
    

    Then define a new class in your css file:

    .hidden { display: none; }
    

    Lastly, in your StepPanel.js file change the rendering approach of steps to this. We're going to render all of steps:

    {props.steps.map((item) => (
        <div
          className={`steps-content ${
            item.step !== activeStep + 1 && "hidden"
          }`}
        >
          {item.content}
        </div>
    ))}
    

    As you can see, we are checking every step if its step number is equal to the currently active step. You can change a forked version of your sandbox here.