Open In App

What is the role of the state in form handling?

Last Updated : 09 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

State management is a critical aspect of React applications, and it plays a significant role in form handling. Forms are essential for user interaction and data input, and React’s state allows us to control and manage the data within these forms dynamically. In this article, we will explore the pivotal role that the state plays in handling forms in React applications, covering various approaches and best practices.

We will discuss the following approaches to understand the role of states in Form Handling:

Steps to Handle Forms with State:

  • Determine whether to use controlled or uncontrolled components based on your project’s requirements and constraints.
  • Initialize the component’s state to hold the form data.
  • Create event handlers to update the state when form elements change.
  • Access the form data from the component’s state when submitting the form.are

package.json:

"dependencies": {    "react": "^17.0.2",    "react-dom": "^17.0.2"}

Approach 1: Using React Class Component:

We use a React class component to create a simple login form. The state is used to store the username and password entered by the user. The handleChange method updates the state as the user types in the input fields, and the handleSubmit method handles the form submission.

Example: This example implements the above mentioned approach.

Javascript




'use client'
import React from 'react';
 
class LoginForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            password: ''
        };
    }
 
    handleChange =
        (event) => {
            const { name, value } = event.target;
            this.setState({
                [name]: value
            });
        }
 
    handleSubmit =
        (event) => {
            event.preventDefault();
            // Handle form submission, e.g., by sending data to an API
            console.log('Submitting', this.state);
        }
 
    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <label>
                    Username:
                    <input type="text" name="username"
                        value={this.state.username}
                        onChange={this.handleChange} />
                </label>
                <br />
                <label>
                    Password:
                    <input type="password" name="password"
                        value={this.state.password}
                        onChange={this.handleChange} />
                </label>
                <br />
                <button type="submit">
                    Submit
                </button>
            </form>
        );
    }
}
 
export default LoginForm;


Output:

Untitled-video---Made-with-Clipchamp-(8)

Approach 2: Using React Hooks:

In this example, we achieve the same functionality as the previous one but using React function component with Hooks. The useState hook is used to manage the form’s state, and the form handling is performed similarly.

Example: This example implements the above mentioned approach.

Javascript




'use client'
import React,
{
    useState
} from 'react';
 
function LoginForm() {
    const [formData, setFormData] = useState({
        username: '',
        password: '',
        email: ''
    });
 
    const handleChange =
        (event) => {
            const { name, value } = event.target;
            setFormData(prevState => ({
                ...prevState,
                [name]: value
            }));
        };
 
    const handleSubmit =
        (event) => {
            event.preventDefault();
            // Simple validation for email
            if (!formData.email) {
                alert('Email is required');
                return;
            }
            // Handle form submission, e.g., by sending data to an API
            console.log('Submitting', formData);
        };
 
    return (
        <form onSubmit={handleSubmit}>
            <label>
                Username:
                <input type="text" name="username"
                    value={formData.username}
                    onChange={handleChange} />
            </label>
            <br />
            <label> {/* Added label for email */}
                Email:
                <input type="email" name="email"
                    value={formData.email}
                    onChange={handleChange} />
            </label>
            <br />
            <label>
                Password:
                <input type="password" name="password"
                    value={formData.password}
                    onChange={handleChange} />
            </label>
            <br />
            <button type="submit">Submit</button>
        </form>
    );
}
 
export default LoginForm;


Output:

Untitled-video---Made-with-Clipchamp-(9)

Conclusion:

In conclusion, state plays a crucial role in handling forms in React applications, whether through controlled or uncontrolled components. Understanding when and how to use state in form handling is essential for creating interactive and user-friendly web applications.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads