Say I have a wizard-like view with an arbitrary number of steps:
const StepsComponent = () => {
const [stage, setStage] = useState(1);
const stageProps = {stage, setStage};
const stageMachine = () => {
switch (stage) {
case 1:
return <One {...stageProps} />;
case 2:
return <Two {...stageProps} />;
case 3:
return <Three {...stageProps} />;
default:
return <One {...stageProps} />;
}
};
return (
<>
{stageMachine()}
</>
);
}
Are there more elegant ways of handling such cases, other than switch statements or ternary expressions?
If I would have wizards with 10+ steps, then it'd be a real mess to manage it.
Probably I could do something like this but this seems hacky, doesn't it?
const stageMachine = Object.freeze({
1: <One {...stageProps} />,
2: <Two {...stageProps} />,
3: <Three {...stageProps} />
});
Also I don't like the idea of invoking stageMachine function in return, it is considered a bad practice?
You can try this
const StepsComponent = () => {
const [stage, setStage] = useState(1);
return (
<>
{stage === 1 && <One />}
{stage === 2 && <Thow />}
{stage === 3 && <Three />}
</>
);
}