Open In App

How To Reset a React-Bootstrap Form After Submit?

Last Updated : 13 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Forms are one of the most useful elements in web applications. It allows users to input their credentials and submit those data. There are many types of forms present (User Registration, Login, Feedback Form etc).

In this article, we will see how to reset a React-Bootstrap Form after submission.

Prerequisites

Approach to reset a React-Bootstrap Form after submit

  • At first, we need to store the form data in the "formData" state object (name, email, password). It can help to track input values and update them.
  • There is a function named "handleChange()" which is used to change the form inputs. It updates the corresponding field in the "formData" object in real time.
  • There is another function named "handleSubmit()" where you need to specify "e.preventDefault()" for default behaviour. This function validates whether all form fields are filled or not. If not, it shows an alert. If all fields are filled, the form displays a success message and resets.

Steps to Reset a React-Bootstrap Form after submit:

Step 1: Create the React application using the following command.

npx create-react-app react-bootstrap-form
cd react-bootstrap-form

Step 2: Then install the react-bootstrap using the following command.

npm install react-bootstrap bootstrap

Step 3: Add Bootstrap CSS in index.js to style the components.

import 'bootstrap/dist/css/bootstrap.min.css';

Folder Structure

Form-folder
Folder Structure:

Dependencies

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"bootstrap": "^5.3.3",
"react": "^18.3.1",
"react-bootstrap": "^2.10.4",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},

Example: Create the required files and add the given codes.

JavaScript
// index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import 'bootstrap/dist/css/bootstrap.min.css';


const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <React.StrictMode>
        <App />
    </React.StrictMode>
);
reportWebVitals();
JavaScript
// App.js code ...
import React, { useState } from "react";
import {
    Button,
    Form,
    Container,
    Row,
    Col,
    Card,
    Alert,
} from "react-bootstrap";

function App() {
    // Step 1: Define state to manage form data and alerts
    const [formData, setFormData] = useState({
        name: "",
        email: "",
        password: "",
    });

    const [alert, setAlert] = useState({
        show: false,
        message: "",
        variant: "",
    });

    // Step 2: Handle input changes
    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData((prevData) => ({
            ...prevData,
            [name]: value,
        }));

        // Hide alert when user starts typing
        if (alert.show) {
            setAlert({ show: false, message: "", variant: "" });
        }
    };

    // Step 3: Handle form submission
    const handleSubmit = (e) => {
        e.preventDefault();

        // Step 4: Validate the form data
        if (!formData.name || !formData.email || !formData.password) {
            setAlert({
                show: true,
                message: "Please fill out all the fields before submitting!",
                variant: "danger",
            });
            return;
        }

        // Step 5: Show success alert and reset the form
        setAlert({
            show: true,
            message: "Form submitted successfully!",
            variant: "success",
        });

        setFormData({
            name: "",
            email: "",
            password: "",
        });
    };

    return (
        <Container className="mt-5">
            <Row className="justify-content-md-center">
                <Col md={6}>
                    <Card className="shadow-lg p-4 mb-5 bg-white rounded">
                        <Card.Body>
                            <h2 className="text-center mb-4 text-success">
                                React-Bootstrap Form
                            </h2>

                            {/* Show alert if any */}
                            {alert.show && (
                                <Alert
                                    variant={alert.variant}
                                    onClose={() => setAlert({ show: false })}
                                    dismissible
                                >
                                    {alert.message}
                                </Alert>
                            )}

                            <Form onSubmit={handleSubmit}>
                                <Form.Group controlId="formName">
                                    <Form.Label className="text-primary">Name:</Form.Label>
                                    <Form.Control
                                        type="text"
                                        name="name"
                                        value={formData.name}
                                        onChange={handleChange}
                                        placeholder="Enter your name"
                                        className="p-2"
                                    />
                                </Form.Group>

                                <Form.Group controlId="formEmail">
                                    <Form.Label className="text-primary">
                                        Email address:
                                    </Form.Label>
                                    <Form.Control
                                        type="email"
                                        name="email"
                                        value={formData.email}
                                        onChange={handleChange}
                                        placeholder="Enter your email"
                                        className="p-2"
                                    />
                                </Form.Group>

                                <Form.Group controlId="formPassword">
                                    <Form.Label className="text-primary">Password:</Form.Label>
                                    <Form.Control
                                        type="password"
                                        name="password"
                                        value={formData.password}
                                        onChange={handleChange}
                                        placeholder="Enter your password"
                                        className="p-2"
                                    />
                                </Form.Group>

                                <Button variant="primary" type="submit" block className="mt-4">
                                    Submit
                                </Button>
                            </Form>
                        </Card.Body>
                    </Card>
                </Col>
            </Row>
        </Container>
    );
}

export default App;


To start the application run the following command

npm start

Output


Similar Reads