Open In App

How to handle forms in React ?

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:

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:

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:

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




// 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;




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




// 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>
);




/* 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;
}




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

Output:

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




//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;




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




//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>
);




/* 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;
  }




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

Output:


Article Tags :