'Material UI 5 Stepper + react hook form 7
I want multi step form. I have MUI5 and react-hook-form 7. I have 2 form one is signup and second is address. I just want to update this example: https://codesandbox.io/s/unruffled-river-9fkxo?file=/src/MultiStepForm.js:2597-2608.
I tried something like this https://codesandbox.io/s/mui5-react-hook-form-7-multi-step-form-9idkw?file=/src/App.js
but value is reset on step change and also validation is not working.
I also want to get those values in last step and submit first. and Can i create defaultValues object step wise?
const defaultValues = {
"step1": {
firstname: "",
lastname: "",
}
"step2": {
address: "",
city: ""
}
}
because I want to submit first form data. and rest of data on last step. So is this approach is okay? or should I have to do another way?
Can you please help me.
Solution 1:[1]
You can save to values to localStorage and if user go back you can easily set defaultValues.
For example:
useEffect(() => {
if (location.pathname === '/step1') {
setActiveStep(3);
} else if (location.pathname === '/step2') {
setActiveStep(0);
} else if (location.pathname === '/step3') {
setActiveStep(1);
} else if (location.pathname === '/step4') {
setActiveStep(2);
} else {
}
}, [location.pathname]);
Solution 2:[2]
There were a lot of errors in your code. I have changed a few things in it, and you can find the working code here (Works at least)
Here are the errors I found:
- In InputController.js, you were using useForm instead of useFormContext
const { control } = useForm(); this is wrong
const { control } = useFormContext(); this is correct
- In App.js, firstname and lastname variables (in defaultValues) were written differently from how they were written in the validation schema.
in defaultValues, you wrote firstname, but in validation schema you wrote firstName (notice the difference in camelCase). The same issue was present in the lastname variable. This is why validation was not working.
- I moved the submit button into the App.js so that It can be rendered conditionally. You only want it to show on the last step :)
Also note that you need to add defaultValues as a prop on the controller component for the TextField because it's a controlled component. Check how I solved this in InputController.js. Lastly, react hook form stores the value for you (this is taken care of by spreading the {...field} on the TextField.
Hope this helps.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mert |
| Solution 2 |
