Skip to content

Instantly share code, notes, and snippets.

@maiconrs95
Created March 6, 2024 19:08
Show Gist options
  • Save maiconrs95/4b1563f6cdfc8de0f1373fc865fc3935 to your computer and use it in GitHub Desktop.
Save maiconrs95/4b1563f6cdfc8de0f1373fc865fc3935 to your computer and use it in GitHub Desktop.
React wizard stepper
import * as React from 'react';
const handleNextStep = maxStep => currentStep => {
if (maxStep) {
if (currentStep < maxStep) return currentStep + 1;
return currentStep;
}
return currentStep + 1;
};
const handlePrevStep = step => {
if (step === 0) return step;
return step - 1;
};
const useWizard = ({ maxStep = 0, startStep = 0 } = {}) => {
const [step, setStep] = React.useState(startStep);
React.useEffect(() => {
setStep(startStep);
}, [startStep]);
const nextStep = React.useCallback(() => {
setStep(handleNextStep(maxStep));
}, [maxStep]);
const prevStep = () => setStep(handlePrevStep);
const goToStep = React.useCallback(
stepToGo => {
if (stepToGo < 0) {
setStep(0);
return;
}
if (maxStep) {
if (stepToGo > maxStep) {
setStep(maxStep);
return;
}
setStep(stepToGo);
return;
}
setStep(stepToGo);
},
[maxStep]
);
const reset = React.useCallback(() => setStep(0), []);
return {
step,
prevStep,
nextStep,
goToStep,
reset,
isFirstStep: startStep ? step === startStep : step === 0,
isLastStep: maxStep && step === maxStep,
maxStep,
};
};
export default useWizard;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment