Open In App

How to handle forms in React ?

Last Updated : 30 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In React, Form handling is one of the basic and important concepts that every developer should learn about. Forms are used to collect the data so that we can use the data for various purposes. This article, lets us understand form handling in React along with examples.

Prerequisites:

Form Attributes in React:

  • input: The <input>’ tag allows users to enter the form data in various forms including text, radio, button, and checkbox, etc.
  • label: The <label>’ tag represents the label of the particular input field.
  • onChange: The onChange is an attribute of ‘<input>’ tag, which is being triggered by a change in the particular input tag and calls the respective handler method.

Steps to Create React Application And Installing Module:

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

npx create-react-app form-demo

Step 2: After creating your project folder i.e. form-demo, move to it using the following command:

cd form-demo

Step 3: After setting up the react environment on your system, we can start by creating an App.js file and create a directory by the name of components in which we will write our desired function.

Project Structure:

1

project structure

The updated dependencies in package.json file will look like:

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

Approach to handle forms in React:

  • Initialization:
    • This part consists of Initializing the variables and state of the form. To manage the state we are using useState() hook and initialized the name and email.
  • Event Handler:
    • The below example consists two handler methods:
      • handleChange(): The handleChange() method stores the updated values as a name and value pair when-ever there is a change occurred. It copies the data everytime into the Data object using setData method.
      • handleSubmit(): The handlesubmit() method console logs the collected form data into the console in the form of an Object. It also handles the default behaviour of reloading the entire page for every change in the form using the preventDefault() method.
  • Form Structure:
    • The basic form structure which contains the ‘<input>’ tag which allows the user to enter an input long with type attribute, placeholder etc. The each input field calls the handleChange() method using onChange attribute.
    • The submit button triggers the handleSubmit() method and console logs the form data where ever the submit button is clicked.

Example-1: let’s look at handling a form with two text input fields i.e. name and email

Javascript




// FormHandling.jsx
 
import React, { useState } from 'react';
import './FormHandling.css';
 
const FormHandling = () => {
    const [Data, setData] = useState({
        name: '',
        email: '',
    });
 
    const handleChange = (e) => {
        const { name, value } = e.target;
        setData({
            ...Data,
            [name]: value,
        });
    };
 
    const handleSubmit = (e) => {
        e.preventDefault();
        console.log('Form data submitted:', Data);
    };
 
    return (
        <form className="form-container"
            onSubmit={handleSubmit}>
            <input type="text" name="name"
                placeholder="Enter the name"
                value={Data.name}
                onChange={handleChange} />
            <input type="email" name="email"
                placeholder="Enter the email"
                value={Data.email}
                onChange={handleChange} />
            <button type="submit">Submit</button>
        </form>
    );
};
 
export default FormHandling;


Javascript




// App.js
import React from 'react';
import FormHandling from './FormHandling';
import './App.css'
 
function App() {
  return (
    <div className="component">
      <FormHandling />
    </div>
  );
}
 
export default App;


Javascript




// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);


CSS




/* FormHandling.css */
 
.form-container {
    max-width: 300px;
    margin: auto;
    padding: 35px;
    border: 1px solid rgb(14, 152, 14);
    border-radius: 5px;
}
 
label {
    display: block;
    margin-bottom: 10px;
}
 
input {
    width: 100%;
    padding: 10px;
    margin-bottom: 20px;
    margin-left: -10px;
    border: 0.5px solid rgb(176, 175, 175);
}
 
button {
    background-color: #4caf50;
    color: white;
    padding: 10px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}
 
button:hover {
    background-color: #45a049;
}


CSS




/*App.css*/
.component {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
}


Output:

Untitledvideo-MadewithClipchamp50-ezgifcom-video-to-gif-converter

Example-2: Let us look at how form handling looks with multiple input fields of different types.

Javascript




//FormHandling.jsx
import './FormHandling.css';
import { useState } from 'react';
 
function FormHandling() {
 
    const [Data, setData] = useState({
        username: '',
        email: '',
        occupation: '',
        gender: '',
        languages: [],
    })
 
    const handleChange = (e) => {
        if (e.target.name === 'languages') {
            let copy = { ...Data }
            if (e.target.checked) {
                copy.languages.push(e.target.value)
            } else {
                copy.languages = copy.languages.filter(el => el !== e.target.value)
            }
            setData(copy)
 
        } else {
            setData(() => ({
                ...Data,
                [e.target.name]: e.target.value
            }))
        }
    }
    const handleSubmit = (e) => {
        e.preventDefault()
        console.log("form submitted: ", Data)
    }
    return (
        <div className="form-container">
            <form onSubmit={handleSubmit}>
                <div className="form-group">
                    <label htmlFor="username"
                        className="form-label">User Name</label>
                    <input className="form-control"
                        placeholder="Enter the username"
                        name="username"
                        onChange={handleChange}
                        value={Data.username} />
                </div>
                <div className="form-group">
                    <label htmlFor="email"
                        className="form-label">Email</label>
                    <input className="form-control"
                        placeholder="Enter the email"
                        name="email"
                        onChange={handleChange}
                        value={Data.email} />
                </div>
                <div className="form-group">
                    <label htmlFor="occupation"
                        className="form-label">Occupation</label>
                    <select className="form-select"
                        name="occupation"
                        onChange={handleChange}
                        value={Data.occupation}
                    >
                        <option>--select--</option>
                        <option value="student">Student</option>
                        <option value="employee">Employee</option>
                        <option value="other">Other</option>
                    </select>
                </div>
                <div className="form-group">
                    <label htmlFor="gender"
                        className="form-label">Gender</label>
                    <div className="radio-group">
                        <div>
                            <input type="radio" name="gender"
                                value="male"
                                onChange={handleChange}
                                checked={Data.gender === 'male'} />
                            <label htmlFor="male">Male</label>
                        </div>
                        <div>
                            <input type="radio" name="gender"
                                value="female"
                                onChange={handleChange}
                                checked={Data.gender === 'female'} />
                            <label htmlFor="female">Female</label>
                        </div>
                        <div>
                            <input type="radio" name="gender"
                                value="other"
                                onChange={handleChange}
                                checked={Data.gender === 'other'} />
                            <label htmlFor="other">Other</label>
                        </div>
                    </div>
                </div>
 
                <div className="form-group">
                    <label htmlFor="gender"
                        className="form-label">Languages</label>
                    <div>
                        <div>
                            <input type="checkbox" name="languages"
                                value="html"
                                onChange={handleChange}
                                checked={Data.languages.indexOf('html') !== -1} />
                            <label htmlFor="html">HTML</label>
                        </div>
                        <div>
                            <input type="checkbox" name="languages"
                                value="css"
                                onChange={handleChange}
                                checked={Data.languages.indexOf('css') !== -1} />
                            <label htmlFor="css">CSS</label>
                        </div>
                        <div>
                            <input type="checkbox" name="languages"
                                value="javascript"
                                onChange={handleChange}
                                checked={Data.languages.indexOf('javascript') !== -1} />
                            <label htmlFor="javascript">Javascript</label>
                        </div>
                    </div>
                </div>
                <div className="form-group">
                    <button className="btn" type="submit" >Submit</button>
                </div>
            </form>
        </div>
    );
}
 
export default FormHandling;


Javascript




// App.js
import React from 'react';
import FormHandling from './FormHandling';
import './App.css'
 
function App() {
  return (
    <div className="component">
      <FormHandling />
    </div>
  );
}
 
export default App;


Javascript




//index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);


CSS




/* FormHandling.css */
.form-container {
    width: 550px;
    margin: auto;
    padding: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
  }
   
  .form-group {
    margin-bottom: 20px;
  }
   
  .form-label {
    display: block;
    margin-bottom: 5px;
  }
   
  .form-control,
  .form-select,
  .form-check input {
    width: 100%;
    padding: 8px;
    box-sizing: border-box;
  }
   
  .form-check label {
    margin-left: 5px;
  }
   
  .btn {
    background-color: #4caf50;
    color: white;
    padding: 10px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
  }
   
  .btn:hover {
    background-color: #45a049;
  }
  .radio-group {
    display: flex;
    gap: 10px;
  }
   
  .radio-group div {
    display: flex;
    align-items: center;
  }
   
  .radio-group input {
    margin-right: 5px;
  }


CSS




/*App.css*/
.component {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100vh;
}


Output:

Untitledvideo-MadewithClipchamp49-ezgifcom-video-to-gif-converter



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads