How to Build a Multi-Step Form in React.js Using Bootstrap
To build a multi-step form in React.js using Bootstrap, you can follow these general steps:
- Install Bootstrap and React-Bootstrap packages using npm or yarn.
npm install bootstrap react-bootstrap2. Create a new React component for your multi-step form. This component will contain the form fields and the logic for handling the form submission.
Get Nawaz Danish’s stories in your inbox
Join Medium for free to get updates from this writer.
3. Use React-Bootstrap components to create the form fields and buttons. The ProgressBar component can be used to show the progress of the form submission. In the component's state, we use step to keep track of the current step and formData to store the form data as it's entered.
4. Use conditional rendering to show the appropriate form fields based on the current step. We use step to determine which fields to show and which buttons to enable/disable.
import React, { useState } from 'react';
import { Form, Button, ProgressBar } from 'react-bootstrap';
const MultiStepForm = () => {
const [step, setStep] = useState(1);
const [formData, setFormData] = useState({});
const handleNext = () => {
setStep(step + 1);
};
const handlePrevious = () => {
setStep(step - 1);
};
const handleInputChange = (event) => {
const { name, value } = event.target;
setFormData({ ...formData, [name]: value });
};
const handleSubmit = (event) => {
event.preventDefault();
// handle form submission
};
return (
<Form onSubmit={handleSubmit}>
<ProgressBar now={(step / 3) * 100} />
{step === 1 && (
<Form.Group controlId="formStep1">
<Form.Label>Name</Form.Label>
<Form.Control
type="text"
name="name"
value={formData.name}
onChange={handleInputChange}
/>
</Form.Group>
)}
{step === 2 && (
<Form.Group controlId="formStep2">
<Form.Label>Email</Form.Label>
<Form.Control
type="email"
name="email"
value={formData.email}
onChange={handleInputChange}
/>
</Form.Group>
)}
{step === 3 && (
<Form.Group controlId="formStep3">
<Form.Label>Message</Form.Label>
<Form.Control
as="textarea"
rows={3}
name="message"
value={formData.message}
onChange={handleInputChange}
/>
</Form.Group>
)}
<div className="d-flex justify-content-between">
{step > 1 && (
<Button variant="secondary" onClick={handlePrevious}>
Previous
</Button>
)}
{step < 3 ? (
<Button variant="primary" onClick={handleNext}>
Next
</Button>
) : (
<Button variant="primary" type="submit">
Submit
</Button>
)}
</div>
</Form>
);
};
export default MultiStepForm;5. Add event handlers to handle user input, navigation between steps, and form submission. The handleInputChange function updates the formData state as the user types. The handleNext and handlePrevious functions update the step state to navigate between steps. The handleSubmit function prevents the default form submission behavior and can be used to send the form data to a server.
6. Export the MultiStepForm component and use it in your application.
Follow us: Nawaz Danish





