Multi-step viewer hook
formcn/use-multi-step-viewerFreeHook
Multi-step viewer hook
Install it
npx shadcn@latest add https://formcn.dev/r/use-multi-step-viewer.jsonSource
1'use client'2import type { JSX } from 'react'3import { createContext, type ReactNode, useContext, useState } from 'react'45export interface Stepfields {6 fields: string[]7 component: JSX.Element8}910export interface UseMultiFormStepsReturn {11 steps: Stepfields[]12 currentStepIndex: number13 currentStepData: Stepfields14 progress: number15 isFirstStep: boolean16 isLastStep: boolean17 goToNext: () => Promise<boolean>18 goToPrevious: () => void19 goToFirstStep: () => void20 goToStep: (stepNumber: number) => void21 setSteps: (newSteps: Stepfields[]) => void22}2324// Context type25interface MultiStepFormContextType extends UseMultiFormStepsReturn {}2627// Create context28const MultiStepFormContext = createContext<MultiStepFormContextType | null>(29 null,30)3132// Provider props33interface MultiStepFormProviderProps {34 children: ReactNode35 stepsFields: Stepfields[]36 onStepValidation?: (step: Stepfields) => Promise<boolean> | boolean37}3839// Provider component40export function MultiStepFormProvider({41 children,42 stepsFields,43 onStepValidation,44}: MultiStepFormProviderProps) {45 const [steps, setStepsState] = useState<Stepfields[]>(stepsFields)46 const [currentStepIndex, setCurrentStepIndex] = useState(1)4748 const goToNext = async () => {49 const currentStepData = steps[currentStepIndex - 1]5051 if (onStepValidation) {52 const isValid = await onStepValidation(currentStepData)53 if (!isValid) return false54 }5556 if (currentStepIndex < steps.length) {57 setCurrentStepIndex((prev) => prev + 1)58 return true59 }60 return false61 }6263 const goToPrevious = () => {64 if (currentStepIndex > 1) {65 setCurrentStepIndex((prev) => prev - 1)66 }67 }6869 const goToFirstStep = () => {70 setCurrentStepIndex(1)71 }7273 const goToStep = (stepNumber: number) => {74 if (stepNumber >= 1 && stepNumber <= steps.length) {75 setCurrentStepIndex(stepNumber)76 }77 }7879 const setSteps = (newSteps: Stepfields[]) => {80 setStepsState(newSteps)81 // Reset to first step if current step is out of bounds82 if (currentStepIndex > newSteps.length) {83 setCurrentStepIndex(1)84 }85 }8687 const value: MultiStepFormContextType = {88 steps,89 currentStepIndex: currentStepIndex,90 currentStepData: steps[currentStepIndex - 1],91 progress: (currentStepIndex / steps.length) * 100,92 isFirstStep: currentStepIndex === 1,93 isLastStep: currentStepIndex === steps.length,94 goToNext,95 goToPrevious,96 goToFirstStep,97 goToStep,98 setSteps,99 }100101// … truncated
Files it writes
More from formcn
All 9 items| Component | Registry | Kind | Access | Installs | Command |
|---|---|---|---|---|---|
| file upload hookuse-file-upload | formcn | Hooks | Free | no deps |
