How to handle forms in React ?
source link: https://www.geeksforgeeks.org/how-to-handle-forms-in-react/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
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:
- 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:
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.
- The below example consists two handler methods:
- 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
- Javascript
- 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; |
Output:
Example-2: Let us look at how form handling looks with multiple input fields of different types.
- Javascript
- Javascript
- 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; |
Output:
Learn to code easily with our course Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!
Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK