C:\Users\Administrator\Desktop\reactrouter\src\Containers\Navigator\Navigator.tsx
import React from "react";
import "./Navigator.css";
import { useStepper } from "./../../hooks/useStepper";
export const Navigator: React.FC = ({ children }) => {
const { nextStepAction, previousStepAction, cantProceed, cantGoBack } = useStepper();
return (
<section className="navigator-main__container">
<div className="navigator-main__content">{children}</div>
<div className="navigator-button__container">
<button
disabled={cantGoBack}
onClick={previousStepAction}
className="btn-secondary"
>
BACK
</button>
<button
disabled={cantProceed}
className="btn-primary"
onClick={nextStepAction}
>
NEXT
</button>
</div>
</section>
);
};
import { useEffect, useState, useCallback } from "react";
import { useHistory } from "react-router-dom";
import { assert } from "../../util";
import { steps as currentSteps } from "../../routes";
export const useStepper = () => {
const history = useHistory();
const getCurrentStepIndex = useCallback(
() => currentSteps.findIndex(step => step.path === history.location.pathname), [history.location.pathname]
);
const [currentStep, setCurrentStep] = useState(getCurrentStepIndex());
const nextStepAction = useCallback(() => {
const index = getCurrentStepIndex();
if (index === currentSteps.length - 1) {
return;
}
setCurrentStep(index + 1);
}, [getCurrentStepIndex]);
const previousStepAction = useCallback(() => {
const index = getCurrentStepIndex();
if (index === 0) {
return;
}
setCurrentStep(index - 1);
}, [getCurrentStepIndex]);
useEffect(() => {
if (currentStep === -1) {
return;
}
const { path } = currentSteps[currentStep];
history.push({
pathname: path,
state: { previousPath: history.location.pathname }
});
}, [currentStep, history]);
return {
currentSteps,
currentStep,
nextStepAction,
previousStepAction,
cantProceed: currentStep === currentSteps.length - 1,
cantGoBack: currentStep <= 0
};
};