antd v4 - Steps and Form

Viewed 6742

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!

2 Answers

Although the above answer works, I prefer not to use CSS to hide and show steps as it defeats the purpose of the way React only renders the required components.

Antd actually has a built-in way of handling this in their documentation. All you need to do is update the below code.

const formData = form.getFieldsValue();

to

const formData = form.getFieldsValue(true);

This will return the value of all the fields not just the hidden ones see their documentation: https://ant.design/components/form/#API;

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.

Related