### Install react-use-wizard
Source: https://github.com/devrnt/react-use-wizard/blob/main/README.md
Install the library using yarn.
```bash
yarn add react-use-wizard
```
--------------------------------
### Basic Wizard Setup
Source: https://github.com/devrnt/react-use-wizard/blob/main/README.md
Set up a basic wizard component by wrapping steps with the Wizard component and using the useWizard hook within individual steps.
```jsx
import * as React from 'react';
import { Wizard, useWizard } from 'react-use-wizard';
const App = () => (
);
const Step1 = () => {
const { handleStep, previousStep, nextStep } = useWizard();
// Attach an optional handler
handleStep(() => {
alert('Going to step 2');
});
return (
<>
>
);
};
```
--------------------------------
### Install React Use Wizard
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
Install the library using yarn or npm. Ensure React version is 16.8.0 or higher.
```bash
yarn add react-use-wizard
# or
npm install react-use-wizard
```
--------------------------------
### Basic Wizard Usage with useWizard Hook
Source: https://github.com/devrnt/react-use-wizard/blob/main/README.md
Demonstrates the fundamental setup of a wizard component using the `Wizard` component and the `useWizard` hook. It shows how to access various wizard states and control methods like `nextStep`, `previousStep`, and `goToStep`. The `handleStep` method is shown for optional step transitions.
```javascript
import * as React from 'react';
import { Wizard, useWizard } from 'react-use-wizard';
const App = () => (
);
const Step1 = () => {
const {
isLoading,
isLastStep,
isFirstStep,
activeStep,
stepCount,
previousStep,
nextStep,
goToStep,
handleStep,
} = useWizard();
// This handler is optional
handleStep(() => {
alert('Going to step 2');
});
return (
<>
Step 1
{isLoading &&
loading...
}
Has next step: {!isLastStep ? '✅' : '⛔'}
Has previous step : {!isFirstStep ? '✅' : '⛔'}
Active step: {activeStep + 1}
>
);
};
```
--------------------------------
### Basic Wizard Component Setup
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
Set up the Wizard component with optional header, footer, and onStepChange callback. Each direct child of Wizard is treated as a step.
```tsx
import * as React from 'react';
import { Wizard } from 'react-use-wizard';
const Header = () =>
My Multi-Step Form
;
const Footer = () =>
Footer — shown on every step
;
const App = () => (
}
footer={}
startIndex={0}
onStepChange={(stepIndex) => console.log('Moved to step', stepIndex)}
>
);
```
--------------------------------
### goToStep
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
Navigates the wizard directly to a specified step using its zero-based index. This action bypasses any `handleStep` handlers. A development-time warning is logged if the provided index is out of bounds.
```APIDOC
## `goToStep` — Jumping to a Specific Step
`goToStep(stepIndex)` navigates directly to any step by its zero-based index without triggering any `handleStep` handler. It logs a warning in development if the index is out of bounds.
```tsx
const StepNavigation = () => {
const { goToStep, activeStep, stepCount } = useWizard();
return (
);
};
```
```
--------------------------------
### startIndex
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
A prop for the `` component that sets the initial active step. This is useful for features like restoring user progress or deep-linking into specific wizard sections.
```APIDOC
## `startIndex` — Starting at a Specific Step
The `startIndex` prop on `` sets the initial active step. Useful for restoring progress or deep-linking into a specific part of the wizard.
```tsx
const ResumableWizard = () => {
// Restore last saved step from storage
const savedStep = parseInt(localStorage.getItem('wizardStep') ?? '0', 10);
return (
localStorage.setItem('wizardStep', String(index))}
>
);
};
```
```
--------------------------------
### Set Initial Wizard Step with startIndex
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
The `startIndex` prop on the `` component allows setting the initial active step, useful for resuming progress or deep-linking.
```tsx
const ResumableWizard = () => {
// Restore last saved step from storage
const savedStep = parseInt(localStorage.getItem('wizardStep') ?? '0', 10);
return (
localStorage.setItem('wizardStep', String(index))}
>
);
};
```
--------------------------------
### Async Step Handlers in useWizard
Source: https://github.com/devrnt/react-use-wizard/blob/main/README.md
Illustrates how to use asynchronous functions or functions returning promises with the `handleStep` method for step transitions. This is useful for operations like API calls before proceeding to the next step.
```typescript
const Step1 = () => {
const { handleStep } = useWizard();
// Async function
handleStep(async () => {
await fetch(...);
});
// OR
// Return promise
handleStep(() => {
return fetch(...);
});
...
}
```
--------------------------------
### Animating Step Transitions with `wrapper`
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
Use the `wrapper` prop with `framer-motion`'s `AnimatePresence` to add enter/exit animations to step content. Ensure `initial={false}` and `exitBeforeEnter` are set on `AnimatePresence` for correct animation behavior.
```tsx
import { AnimatePresence, motion } from 'framer-motion';
import { Wizard, useWizard } from 'react-use-wizard';
const AnimatedStep: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const { activeStep } = useWizard();
return (
{children}
);
};
const AnimatedWizard = () => (
}>
);
```
--------------------------------
### Jump to Specific Step with goToStep
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
Use `goToStep(stepIndex)` to navigate directly to a step by its zero-based index. This bypasses any `handleStep` handlers and logs a development warning for out-of-bounds indices.
```tsx
const StepNavigation = () => {
const { goToStep, activeStep, stepCount } = useWizard();
return (
);
};
```
--------------------------------
### handleStep
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
Registers a synchronous or asynchronous callback to be executed before advancing to the next step. If the handler rejects or throws an error, the wizard remains on the current step. `isLoading` state reflects the pending status of async handlers.
```APIDOC
## `handleStep` — Attaching Step Handlers
`handleStep` registers a sync or async callback on the current step. When `nextStep()` is called, the handler executes first. If it resolves (or returns normally), the wizard advances. If it throws or rejects, the wizard stays on the current step and re-throws the error for the caller to handle. `isLoading` reflects the pending state of an async handler.
```tsx
import * as React from 'react';
import { useWizard } from 'react-use-wizard';
const SubmitStep = () => {
const { handleStep, isLoading, nextStep } = useWizard();
// Async handler — wizard will not advance if this rejects
handleStep(async () => {
const response = await fetch('/api/submit', {
method: 'POST',
body: JSON.stringify({ name: 'John' }),
});
if (!response.ok) {
throw new Error('Submission failed'); // wizard stays on this step
}
});
return (
);
};
// Sync handler with try/catch in caller
const ValidationStep = () => {
const { handleStep, nextStep } = useWizard();
const [error, setError] = React.useState(null);
handleStep(() => {
const value = (document.getElementById('email') as HTMLInputElement).value;
if (!value.includes('@')) throw new Error('Invalid email');
});
const handleNext = async () => {
try {
await nextStep();
} catch (err) {
setError((err as Error).message);
}
};
return (
{error &&
{error}
}
);
};
```
```
--------------------------------
### Wizard with Header, Footer, and Wrapper
Source: https://github.com/devrnt/react-use-wizard/blob/main/README.md
Configure the Wizard component with custom header, footer, and wrapper components. The wrapper is applied exclusively around the active step.
```jsx
// Example: show the active step in the header
const Header = () =>
I am the header component
;
// Example: show the "previous" and "next" buttons in the footer
const Footer = () =>
I am the footer component
;
// Example: Wrap steps in an `;
const App = () => {
return (
}
footer={}
wrapper={}
>
);
};
```
--------------------------------
### Wizard Component
Source: https://github.com/devrnt/react-use-wizard/blob/main/README.md
The Wizard component is used to wrap your steps. Each child component will be treated as an individual step. You can pass shared header and footer components that should always be present.
```APIDOC
## Wizard Component
### Description
Wraps individual step components, allowing for shared header, footer, and step-specific logic.
### Props
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Props
- **startIndex** (number) - Optional - Indicate the wizard to start at the given step. Default: 0
- **header** (React.ReactNode) - Optional - Header that is shown above the active step.
- **footer** (React.ReactNode) - Optional - Footer that is shown below the active step.
- **onStepChange** ((stepIndex) => void) - Optional - Callback invoked with the new step index when the wizard changes steps.
- **wrapper** (React.ReactElement) - Optional - Optional wrapper that is exclusively wrapped around the active step component. It is not wrapped around the `header` and `footer`.
- **children** (React.ReactNode) - Required - Each child component will be treated as an individual step.
### Request Example
```javascript
// Example: show the active step in the header
const Header = () =>
I am the header component
;
// Example: show the "previous" and "next" buttons in the footer
const Footer = () =>
I am the footer component
;
// Example: Wrap steps in an `;
const App = () => {
return (
}
footer={}
wrapper={}
>
);
};
```
### Response
#### Success Response (200)
N/A (This is a component, not an endpoint)
#### Response Example
N/A
```
--------------------------------
### Wizard Control Methods
Source: https://github.com/devrnt/react-use-wizard/blob/main/README.md
These methods allow direct control over the wizard's progression and state management.
```APIDOC
## nextStep
### Description
Navigates the wizard to the next step in the sequence.
### Method
`nextStep()`
### Parameters
None
### Response
- `Promise`: A promise that resolves when the step transition is complete.
```
```APIDOC
## previousStep
### Description
Navigates the wizard to the previous step in the sequence.
### Method
`previousStep()`
### Parameters
None
### Response
`void`
```
```APIDOC
## goToStep
### Description
Navigates the wizard to a specific step identified by its index.
### Method
`goToStep(stepIndex: number)`
### Parameters
#### Path Parameters
- **stepIndex** (number) - Required - The index of the step to navigate to.
```
```APIDOC
## handleStep
### Description
Attaches a callback function that will be executed when `nextStep` is called. This is useful for performing actions (e.g., data fetching, validation) before proceeding to the next step.
### Method
`handleStep(handler: Handler)`
### Parameters
#### Path Parameters
- **handler** (Handler) - Required - A callback function that can be either synchronous or asynchronous. If asynchronous, it should return a Promise.
```
--------------------------------
### nextStep
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
An asynchronous function that first executes any registered `handleStep` handler and then advances the wizard to the next step. If no handler is present, it advances immediately. It has no effect if called on the last step.
```APIDOC
## `nextStep` — Advancing the Wizard
`nextStep` is an async function that first runs any handler registered via `handleStep`, then moves the wizard to the next step. If no handler is registered it advances immediately. It does nothing if already on the last step.
```tsx
const StepWithNext = () => {
const { nextStep, isLoading, isLastStep } = useWizard();
const handleClick = async () => {
try {
await nextStep(); // runs handler → advances (or stays on error)
} catch (err) {
console.error('Could not advance:', err);
}
};
return (
);
};
```
```
--------------------------------
### Dynamic Step Rendering
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
Render wizard steps conditionally based on state or from an array. The `stepCount` provided by `useWizard` automatically updates to reflect the current number of rendered steps.
```tsx
const DynamicWizard = () => {
const [includeOptional, setIncludeOptional] = React.useState(false);
return (
<>
{includeOptional && }
>
);
};
```
--------------------------------
### previousStep
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
Synchronously navigates the wizard back to the previous step. This function has no effect when called on the first step. Any registered `handleStep` handler is cleared upon calling `previousStep`.
```APIDOC
## `previousStep` — Going Back
`previousStep` synchronously returns to the prior step. It does nothing when called on the first step. Calling it also clears any registered `handleStep` handler.
```tsx
const BackButton = () => {
const { previousStep, isFirstStep } = useWizard();
return (
);
};
```
```
--------------------------------
### Using the useWizard Hook in a Step
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
Access wizard state and navigation methods within a step component using the useWizard hook. Ensure the component is a descendant of the Wizard component.
```tsx
import * as React from 'react';
import { useWizard } from 'react-use-wizard';
const StepOne = () => {
const {
nextStep,
previousStep,
goToStep,
handleStep,
isLoading,
activeStep,
stepCount,
isFirstStep,
isLastStep,
} = useWizard();
return (
Step {activeStep + 1} of {stepCount}
{isLoading &&
Processing...
}
);
};
```
--------------------------------
### Integration with React Query Mutations
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
Use `handleStep` to integrate with React Query mutations. The wizard will wait for the mutation to complete before advancing and will remain on the current step if the mutation fails.
```tsx
import { useMutation } from 'react-query';
import { useWizard } from 'react-use-wizard';
const SaveProfileStep = () => {
const { handleStep, nextStep, isLoading } = useWizard();
const [formData, setFormData] = React.useState({ name: '' });
const mutation = useMutation((data: { name: string }) =>
fetch('/api/profile', { method: 'POST', body: JSON.stringify(data) }).then((r) => r.json()),
);
handleStep(() => mutation.mutateAsync(formData));
return (
);
};
```
--------------------------------
### Wizard State Properties
Source: https://github.com/devrnt/react-use-wizard/blob/main/README.md
These properties provide information about the current state of the wizard.
```APIDOC
## isLoading
### Description
Indicates whether the current step handler is in a pending state. This is particularly useful for asynchronous handlers.
### Property
`isLoading` (boolean)
### Value
- `true`: The handler promise is currently pending.
- `false`: The handler has either fulfilled or been rejected.
```
```APIDOC
## activeStep
### Description
Represents the index of the currently active step in the wizard.
### Property
`activeStep` (number)
```
```APIDOC
## stepCount
### Description
Indicates the total number of steps available in the wizard.
### Property
`stepCount` (number)
```
```APIDOC
## isFirstStep
### Description
A boolean flag indicating whether the current active step is the first step in the wizard.
### Property
`isFirstStep` (boolean)
```
```APIDOC
## isLastStep
### Description
A boolean flag indicating whether the current active step is the last step in the wizard.
### Property
`isLastStep` (boolean)
```
--------------------------------
### Register Async Step Handler with handleStep
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
Use `handleStep` to register an asynchronous handler. The wizard will not advance if the handler rejects. `isLoading` reflects the pending state.
```tsx
import * as React from 'react';
import { useWizard } from 'react-use-wizard';
const SubmitStep = () => {
const { handleStep, isLoading, nextStep } = useWizard();
// Async handler — wizard will not advance if this rejects
handleStep(async () => {
const response = await fetch('/api/submit', {
method: 'POST',
body: JSON.stringify({ name: 'John' }),
});
if (!response.ok) {
throw new Error('Submission failed'); // wizard stays on this step
}
});
return (
);
};
```
--------------------------------
### Advance Wizard Step with nextStep
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
The `nextStep` function advances the wizard to the next step after executing any registered `handleStep` handler. It handles errors thrown by the handler and does nothing if already on the last step.
```tsx
const StepWithNext = () => {
const { nextStep, isLoading, isLastStep } = useWizard();
const handleClick = async () => {
try {
await nextStep(); // runs handler → advances (or stays on error)
} catch (err) {
console.error('Could not advance:', err);
}
};
return (
);
};
```
--------------------------------
### Wizard Component
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
The Wizard component acts as a container for all wizard steps. It manages the active step state and provides context to its descendants. Optional header and footer components can be rendered persistently above and below the active step.
```APIDOC
## Wizard Component Props
### Description
Props for the `Wizard` component.
### Props
#### Children
- **children** (`React.ReactNode`) - Required - Each child is one wizard step.
#### Header
- **header** (`React.ReactNode`) - Optional - Rendered above the active step on every step.
#### Footer
- **footer** (`React.ReactNode`) - Optional - Rendered below the active step on every step.
#### Start Index
- **startIndex** (`number`) - Optional - Default: `0` - Index of the step to start on.
#### Wrapper
- **wrapper** (`React.ReactElement`) - Optional - Wraps only the active step (e.g., ``).
#### On Step Change
- **onStepChange** (`(stepIndex: number) => void`) - Optional - Callback fired with the new step index on every transition.
```
--------------------------------
### useWizard Hook
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
The useWizard hook provides access to wizard state and navigation methods within any component that is a descendant of the Wizard component. It returns functions to control step progression and state variables indicating the current step's status.
```APIDOC
## useWizard Hook Return Values
### Description
Values returned by the `useWizard` hook.
### Return Values
#### Next Step
- **nextStep** (`() => Promise`) - Advance to the next step; runs the attached handler first.
#### Previous Step
- **previousStep** (`() => void`) - Go back to the previous step.
#### Go To Step
- **goToStep** (`(stepIndex: number) => void`) - Jump to an arbitrary step by zero-based index.
#### Handle Step
- **handleStep** (`(handler: Handler) => void`) - Attach a sync or async callback to run before advancing.
#### Is Loading
- **isLoading** (`boolean`) - `true` while an async `handleStep` handler is pending.
#### Active Step
- **activeStep** (`number`) - Zero-based index of the currently active step.
#### Step Count
- **stepCount** (`number`) - Total number of steps.
#### Is First Step
- **isFirstStep** (`boolean`) - `true` when on the first step.
#### Is Last Step
- **isLastStep** (`boolean`) - `true` when on the last step.
```
--------------------------------
### Shared Header and Footer for Navigation
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
Pass persistent navigation controls like 'Back' and 'Next' buttons to the `header` or `footer` props of the `Wizard` component. This avoids duplication and allows access to wizard state and methods via `useWizard`.
```tsx
import { Wizard, useWizard } from 'react-use-wizard';
const WizardFooter = () => {
const { previousStep, nextStep, isFirstStep, isLastStep, isLoading, activeStep, stepCount } =
useWizard();
return (
);
};
const App = () => (
}>
);
```
--------------------------------
### useWizard Hook
Source: https://github.com/devrnt/react-use-wizard/blob/main/README.md
The useWizard hook provides access to wizard methods and properties. It must be used within a component wrapped by the Wizard component.
```APIDOC
## useWizard Hook
### Description
Provides access to wizard control methods and state. Must be used within a component rendered inside the `Wizard` component.
### Method Signature
`useWizard()`
### Returns
An object containing wizard control methods and properties:
- `previousStep`: Function to navigate to the previous step.
- `nextStep`: Function to navigate to the next step.
- `goToStep(stepIndex)`: Function to navigate to a specific step by its index.
- `handleStep(callback)`: Function to attach a synchronous or asynchronous handler to be executed before navigating to the next step.
- `activeStep`: The index of the currently active step.
### Remarks
Cannot be used in the same component where `Wizard` is declared.
### Example
```javascript
import { useWizard } from 'react-use-wizard';
const MyStepComponent = () => {
const { previousStep, nextStep, goToStep, handleStep, activeStep } = useWizard();
// Attach an optional handler to be executed before moving to the next step
handleStep(() => {
console.log('Moving to the next step...');
// You can perform async operations here as well
});
return (
Current Step: {activeStep}
);
};
```
```
--------------------------------
### onStepChange
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
A callback function that is invoked with the new step index whenever the active step changes. This event fires regardless of the navigation method used (e.g., `nextStep`, `previousStep`, `goToStep`).
```APIDOC
## `onStepChange` — Reacting to Step Changes
The `onStepChange` callback is invoked with the new step index every time the active step changes, regardless of whether it was triggered by `nextStep`, `previousStep`, or `goToStep`.
```tsx
const TrackedWizard = () => {
const handleStepChange = (stepIndex: number) => {
// Analytics, URL sync, progress persistence, etc.
window.history.replaceState(null, '', `?step=${stepIndex}`);
analytics.track('wizard_step_viewed', { step: stepIndex });
};
return (
);
};
```
```
--------------------------------
### Navigate to Previous Step with previousStep
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
The `previousStep` function synchronously returns to the prior step. It is disabled on the first step and clears any active `handleStep` handler.
```tsx
const BackButton = () => {
const { previousStep, isFirstStep } = useWizard();
return (
);
};
```
--------------------------------
### Register Sync Step Handler with handleStep and Caller Error Handling
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
Register a synchronous handler with `handleStep`. Errors thrown by the handler are caught by the caller using `nextStep` in a try/catch block.
```tsx
// Sync handler with try/catch in caller
const ValidationStep = () => {
const { handleStep, nextStep } = useWizard();
const [error, setError] = React.useState(null);
handleStep(() => {
const value = (document.getElementById('email') as HTMLInputElement).value;
if (!value.includes('@')) throw new Error('Invalid email');
});
const handleNext = async () => {
try {
await nextStep();
} catch (err) {
setError((err as Error).message);
}
};
return (
{error &&
{error}
}
);
};
```
--------------------------------
### React to Step Changes with onStepChange
Source: https://context7.com/devrnt/react-use-wizard/llms.txt
The `onStepChange` callback is triggered with the new step index whenever the active step changes, regardless of the navigation method.
```tsx
const TrackedWizard = () => {
const handleStepChange = (stepIndex: number) => {
// Analytics, URL sync, progress persistence, etc.
window.history.replaceState(null, '', `?step=${stepIndex}`);
analytics.track('wizard_step_viewed', { step: stepIndex });
};
return (
);
};
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.