DonAdam2 / react-dynamic-stepper

Advanced and multi-feature stepper component designed to be incredibly versatile for a variety of workflows and use cases.
MIT License
1 stars 0 forks source link

How to make the next button (without disabling it) not allow to go to the next step until the form inside a step is valid? #3

Closed pj-alvarado10 closed 2 months ago

pj-alvarado10 commented 2 months ago

Hi! I am sorry to bother...

I am using react-dynamic-stepper and in step 2 in the content I have a form in a different component with React-Boostrap like that:

    const [ form, setForm ] = useState<any>(); 
    const [ valuesForm, setValuesForm ] = useState<any>(); 
    const [ isSubmit, setIsSubmit ] = useState(false);

  const steps = [
    (...)
      {
        header: {
          label: TitleStep2,
        },
        content: <MyForm
                    isSubmit={isSubmit}
                    values={ valuesForm } 
                    handleValues={(values: any, form: any) => handleValues(values, form)}
                  />,
        isComplete: true,
        isError: isSubmit && !form?.checkValidity(),
        onClickHandler: () => { handleSubmit() }
      },
  (...)
}];

How can I make the next button (without disabling it) does not let us go to the next step until the form is valid?

I try with this function in stepper component but I dont know if I can avoid that the stepper goes to next page when the form is not valid:

 function handleSubmit(){
      setIsSubmit(true);
      if( !form?.checkValidity() )
      {
        //TODO: how avoid the stepper goes to next step?
        return;
      }
    }

Thank you so much and I am sorry to bother again.

pj-alvarado10 commented 2 months ago

Hi! I already managed to get this behavior!

I use javascript and findElementByClassName of this way:

    function handleSubmit(){
      setIsSubmit(true);
      if( !form.?.checkValidity() )
      {
        const btn = document.getElementsByClassName('prev-btn')[0] as HTMLButtonElement;
        btn?.click();
        return;
      }
    }

Clearly, I must use a className of custom footer:

footerData={{
     prevBtnClassName: 'prev-btn',
 }}

If the library has a better way to get this feature, I would like to know. Anyway, I'm closing the issue. Thank you!!!

Edit: I forgot the property "ref" to navigate to any step programmatically, I suppose this situation is the properly to use this prop, instead of calling the prev button by classname and clicking it, use ref to return to step 2. The final result is:

 function handleRegisterOrder(){
      setIsSubmitRegister(true);
      if( !validForms.registerOrder?.checkValidity() )
      {
        handleChangeComplete(1, false);
        stepperRef.current?.navigateToStep(0);
        return;
      }
    }
DonAdam2 commented 1 month ago

I added a new flag step.footer.isPreventNextClick which will do that for you