| 1 | import { ReactElement, useState } from "react" |
| 2 | |
| 3 | export function useMultistepForm(steps: ReactElement[]) { |
| 4 | const [currentStepIndex, setCurrentStepIndex] = useState(0) |
| 5 | |
| 6 | function next() { |
| 7 | setCurrentStepIndex(i => { |
| 8 | if (i >= steps.length - 1) return i |
| 9 | return i + 1 |
| 10 | }) |
| 11 | } |
| 12 | |
| 13 | function back() { |
| 14 | setCurrentStepIndex(i => { |
| 15 | if (i <= 0) return i |
| 16 | return i - 1 |
| 17 | }) |
| 18 | } |
| 19 | |
| 20 | function goTo(index: number) { |
| 21 | setCurrentStepIndex(index) |
| 22 | } |
| 23 | |
| 24 | return { |
| 25 | currentStepIndex, |
| 26 | step: steps[currentStepIndex], |
| 27 | steps, |
| 28 | isFirstStep: currentStepIndex === 0, |
| 29 | isLastStep: currentStepIndex === steps.length - 1, |
| 30 | goTo, |
| 31 | next, |
| 32 | back, |
| 33 | } |
| 34 | } |