Open In App

What is the role of the state in form handling?

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:

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.




'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:

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.




'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:

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.


Article Tags :