I'm working on Register Form using MaterialUI stepper. Each stepper render a component:
const steps = ['Basic informations', 'Profile', 'Review your registration']
And there's a Register button
at the end step
, click on it should handleSubmit the form data.
I tried to make this concept using this code below, but it didn't work. Can you fix it for me please?
const steps = ['Basic informations', 'Profile', 'Review your registration']
export default function Register() {
const [activeStep, setActiveStep] = React.useState(0)
const [stateRegister, setStateRegister] = useState({})
const [stateProfile, setStateProfile] = useState({})
function getStepContent(step) {
switch (step) {
case 0:
return <BasicForm stateOfRegister={stateOfRegister} />
case 1:
return <ProfileForm stateOfProfile={stateOfProfile} />
case 2:
return <Review stateRegister={stateRegister} stateProfile={stateProfile} />
default:
throw new Error('Unknown step')
}
}
const stateOfRegister = (props) => {
setStateRegister(props)
}
const stateOfProfile = (props) => {
setStateProfile(props)
}
const handleNext = () => {
setActiveStep(activeStep 1)
}
const handleBack = () => {
setActiveStep(activeStep - 1)
}
const handleNavigate = () => {
navigate('/')
}
const handleSubmit = async () => {
const user = { ...stateRegister, ...stateProfile, role: 'user', uid: 'azeq' }
await addUser(user)
}
return (
<React.Fragment>
{getStepContent(activeStep)}
<Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
{activeStep !== 0 && (
<>
<Button onClick={handleBack} sx={{ mt: 3, ml: 1 }}>
Back
</Button>
</>
)}
<Button
variant="contained"
onClick={() => {
handleNext()
{
activeStep === 3 && handleSubmit() //this is my try
}
}}
sx={{ mt: 3, ml: 1 }}
>
{activeStep === steps.length - 1 ? 'Register' : 'Next'}
</Button>
</Box>
</React.Fragment>
)
}
CodePudding user response:
If you change the click handler on the button it might behave the way that you would like.
const onNextClick = () => {
if(activeStep === steps.length - 1)
handleSubmit()
else
handleNext()
}
...
<Button
variant="contained"
onClick={onNextClick}
sx={{ mt: 3, ml: 1 }}
>
{activeStep === steps.length - 1 ? 'Register' : 'Next'}
</Button>
...