top of page
Writer's picturepavithrasenthurai

Forms in REACT

React is a frontend framework which helps us with developing single application. React is an opensource project backed by Meta in which the interactive features such as likes, comments and posts. React application can be tested with jest framework. It is being used for fast and interactive front end, real time data updates and managing complex application stated.


Prerequisites

Create a react web page


Create a react app using the following command

npx create-react-app my-app

If you don't have npx, use the following command

npm install -g create-react-app
create-react-app my-app

Do `npm install` from the project you just created and Type `code .` to launch the visual code Run the command npm run start to start the application


These folders and files will be automatically generated
npm install
npm run start

You can see the application started successfully otherwise check for the error and install necessary libraries

For Example: The error I came across during this process is missing web-vitals, We need run "npm install web-vitals" this will Install the appropriate libraries accordingly.


You will see a web page opening with a react logo, congratulations you have successfully created a react application.

 

Adding a Contact Form


Let's start coding for the web page "Contact FORM"


In React, Hook state refers to the state management capability provided by React's Hooks, specifically using the useState Hook.


What is STATE in REACT


  • State represents dynamic data or information in a component that can change over time. Changes to state trigger React to re-render the component, updating the UI to reflect the new state.

  • useState is used to create and manage state variables in functional components.

  • const ContactForm = () => { }

    Ww are declaring the ContactForm component using arrow function. This is a functional React component.


contact-form.js


Import the React library and the useState hook for our contact form

import React, { useState } from 'react'. 

Declaring State


const [formData, setFormData] = useState({ name: "", email: "", message: "", });

formData

state object to store the current form input values

setFormData

function to update the state

{ name: "", email: "", message: "", }

object with empty strings for name, email and message

const [submittedData, setSubmittedData] = useState([]);

submitted data

an array that stores all the form submissions

setsubmitted data

updates the submitted data state

useState([]

initial state is an empty array

JSX (Rendering)


return <div> <h2>Contact Us</h2> <div style={{ maxWidth: "400px", margin: "auto" }}> 
...
...
</div>
 </div>

Returning the JSX from the function tells the browser to update the shadow DOM and render/refresh the browser.


Add Form tags to build the contact form


<form onSubmit={handleSubmit}>

Contains a div with a header and a form element. The form's onSubmit event calls handleSubmit.


Form Fields

Each input field is controlled by formData:


<input type="text" id="name" name="name" value={formData.name} onChange={handleChange} required style={{ width: "100%", padding: "0.5rem" }} />

 <input  type="email"  id="email"   name="email" value={formData.email}  onChange={handleChange} required style={{ width: "100%", padding: "0.5rem" }} />

  • formData.name is used to load/update the data in the form  onChange calls handleChange to update the state.

  • required keyword ensures that the field cannot be empty and act as a validation.


Buttons


<button type="submit" style={{ padding: "0.5rem 1rem" }}>Submit</button> <button type="reset" style={{ padding: "0.5rem 1rem" }} onClick={() => setFormData({ name: "", email: "", message: "" })}> Reset </button>

Submit button

Triggers handleSubmit and save the forms data and fire the hooks

Reset Button

Clears the form by setting formdata to an empty state


Handling Input Changes


const handleChange = (e) => {
 const { name, value } = e.target; 
 setFormData((prevData) => ({ ...prevData, [name]:  value }));
};


const handleChange

updates the form fields when the user types

HTML element that triggers the event

 { name, value }

Destructures name (input field name) and value (input value) from e.target.

setFormData((prevData) => ({ ...prevData, [name]: value }));

Updates the formData state using the previous state (prevData) and the new value for the field ([name]: value)

Editing Data


const edit = (data, index) => { setFormData(data); submittedData.splice(index, 1); };


const edit

Triggered when the user clicks the edit button

setFormData(data)

Loads the selected data back into the form

submittedData.splice(index, 1)

Removes the selected data from submitted data using splice


Deleting Data


const deleteData = (index) => {
 const array = submittedData.splice(index, 1);  
 setSubmittedData([...submittedData]);
};


const deleteData

triggered when the user clicks the delete button

 { const array = submittedData.splice(index, 1);

removes the data at the specified index using splice

setSubmittedData([...submittedData]); };

updated submitteddata with a new array (using the spread operator)


Handling Form Submission


const handleSubmit = (e) => {
	e.preventDefault(); 
	setSubmittedData([formData, ...submittedData]); 
	setFormData({ name: "", email: "", message: "" });
};


const handleSubmit 

lambda function which triggers on form submission

e.preventDefault()

Prevent the default behavior of the browser and continue with our implementation

setSubmittedData([formData, ...submittedData]);

Add the submitted data to the array add use the hook to update the component

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

Reset the form using the hooks

Table for Submitted Data



   <table style={{ width: "100%", padding: "0.5rem" }}>
                <thead>
                    <tr>
                      <th>Name</th>  <th>Email</th>   <th>Message</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {submittedData.map((data, index) => (
                        <tr key={index}>
                            <td>{data.name}</td> <td>{data.email}</td>
                            <td>{data.message}</td>
                            <td     <button onClick={() => edit(data, index)}> Edit </button>
                                <button onClick={() => deleteData(index)}> delete </button>
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
  • Displays the submitted data in a table format. Uses map to render each item in submittedData as a table row. The "Edit" and "Delete" buttons call their respective functions with the correct index.


Exporting the Component


Makes the ContactForm component available globally by exporting it.


export default ContactForm


The Final Format after combining all declarations and functions


//import the react from react package
import React, { useState } from 'react'; 

// declare contactForm using React Hooks 
const ContactForm = () => {
    const [formData, setFormData] = useState({
        name: "",
        email: "",
        message: "",
    });
// Declare the submitted data as array
const [submittedData, setSubmittedData] = useState([]);

// on change update the formData
const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData((prevData) => ({
            ...prevData,
            [name]: value
        }));
    };

	// onClick of edit, load the data to the form from the table
    const edit = (data, index) => {
        setFormData(data);
        submittedData.splice(index, 1);
    };
	// delete the data from the table
    const deleteData = (index) => {
        const array = submittedData.splice(index, 1);
        setSubmittedData([...submittedData]);
         };

    const handleSubmit = (e) => {
        e.preventDefault(); // Prevent page reload
        setSubmittedData([formData, ...submittedData]); 
        setFormData({ name: "", email: "", message: "" }); 
    };

    return (
        <div >
            <h2>Contact Us</h2>
            <div style={{ maxWidth: "400px", margin: "auto" }}>
                <form onSubmit={handleSubmit}>
                    <div >
                        <label htmlFor="name">Name:</label>
                        <input
                            type="text"
                            id="name"
                            name="name"
                            value={formData.name}
                            onChange={handleChange}
                            required
                            style={{ width: "100%", padding: "0.5rem" }}
                        />
                    </div>

                    <div style={{ marginBottom: "1rem" }}>
                        <label htmlFor="email">Email:</label>
                        <input
                            type="email"
                            id="email"
                            name="email"
                            value={formData.email}
                            onChange={handleChange}
                            required
                            style={{ width: "100%", padding: "0.5rem" }}
                        />
                    </div>

                    <div style={{ marginBottom: "1rem" }}>
                        <label htmlFor="message">Message:</label>
                        <textarea
                            id="message"
                            name="message"
                            value={formData.message}
                            onChange={handleChange}
                            required
                            style={{ width: "100%", padding: "0.5rem" }}
                        />
                    </div>
                    <button type="submit" style={{ padding: "0.5rem 1rem" }}>Submit </button>
                    <button type="reset" style={{ padding: "0.5rem 1rem" }} onClick={() => setFormData({ name: "", email: "", message: "" })}>
                        Reset   </button>
                </form>
            </div>
            <table style={{ width: "100%", padding: "0.5rem" }}>
                <thead>
                    <tr>
                      <th>Name</th>  <th>Email</th>   <th>Message</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    {submittedData.map((data, index) => (
                        <tr key={index}>
                            <td>{data.name}</td> <td>{data.email}</td>
                            <td>{data.message}</td>
                            <td     <button onClick={() => edit(data, index)}>Edit</button>
                                <button onClick={() => deleteData(index)}>delete</button>
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>

    );
};

export default ContactForm;

update App.js


import './App.css';
import ContactForm from './contact-form';

function App() {
  return (
    <div className="App">
      <header className="App-header">
      <ContactForm />
      </header>
    </div>
  );
}

export default App;

Run npm run start from command prompt


This command will trigger the script "start" and run "react-scripts start"

Likewise the other commands such as build and test can also be triggered by npm run.

Do not run the command eject until you are aware of the eject functionality because it may change the project structure to a complex one for advanced scripting.


After executing the command npm run start, it will open a browser.


Try to submit a form information and it will look like below




This conclude the react implementation for contact form.




35 views

Recent Posts

See All
bottom of page