Multi-step Form Wizard in Next.js
Develop a multi-step form wizard with validation, using Next.js's state management to navigate between different form stages and persist data across them.
import { useState } from 'react';
export default function MultiStepForm() {
const [currentStep, setCurrentStep] = useState(0);
const [formData, setFormData] = useState({});
const nextStep = () => setCurrentStep((prevStep) => prevStep + 1);
const prevStep = () => setCurrentStep((prevStep) => prevStep - 1);
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
return (
// Render the form with steps
);
}
This code initializes the multi-step form, manages the current step and form data state, and handles input changes.
const StepOne = ({ handleChange, data }) => (
<div>
<label htmlFor="firstname">First Name:</label>
<input type="text" id="firstname" name="firstname" value={data.firstname || ''} onChange={handleChange} />
// Add other fields and validation as needed
</div>
);
const StepTwo = ({ handleChange, data }) => (
// Define similarly for Step 2
);
const StepThree = ({ handleChange, data }) => (
// Define similarly for Step 3
);
These are the individual form step components. Each accepts a handleChange function and data for controlled inputs.
import { useState } from 'react';
export default function MultiStepForm() {
//... existing code ...
const steps = [
<StepOne handleChange={handleChange} data={formData} />,
<StepTwo handleChange={handleChange} data={formData} />,
<StepThree handleChange={handleChange} data={formData} />
];
return (
<div>
{steps[currentStep]}
<button onClick={prevStep} disabled={currentStep === 0}>Previous</button>
<button onClick={nextStep} disabled={currentStep === steps.length - 1}>Next</button>
</div>
);
}
This code integrates the form step components into the main form and provides navigation buttons with disable state based on the current step.