I'm trying to create a multi-step form in NextJS.Now i'm just conditionally render each step with a state as step number.is there an another better way to do this?
const [showStep, setshowStep] = useState<number>(1);
function RenderStep() {
switch (showStep) {
case 1:
return <StepOne setStep={setshowStep} />;
case 2:
return <StepTwo setStep={setshowStep}/>;
case 3:
return <StepThree setStep={setshowStep}/>;
case 4:
return <StepFour setStep={setshowStep}/>;
default:
return <StepOne setStep={setshowStep} />;
}
}
return (
<div>
<Page>
<Link href="/campaigns">back</Link>
<RenderStep />
</Page>
</div>
);
}
CodePudding user response:
Maybe a simple way would have to create a <Step> component that contains your step content like this:
import {PropsWithChildren} from "react";
interface StepProps {
value: number;
index: number;
}
const Step = (props: PropsWithChildren<StepProps>): JSX.Element | null => {
const {children, index, value} = props;
return index === value ? <>{children}</> : null;
}
Which would allow you afterwards to have something like
<Step index={0} value={showStep}>
// your step 0 content
</Step>
<Step index={1} value={showStep}>
// your step 1 content
</Step>
and so on.
