Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

React - Controlled Components

Managing forms with controlled components

Controlled components in React are those where form data is handled by the component's state. This approach allows you to have complete control over the form elements and their values. This tutorial covers how to manage forms with controlled components in React.

Key Points:

  • Controlled components are form elements whose values are controlled by React state.
  • They provide a single source of truth for form data, making it easier to manage and validate.
  • Controlled components require you to handle form element changes and update the state accordingly.

Creating a Controlled Input

To create a controlled input, you need to set the value of the input to a state variable and update the state variable when the input value changes.

// Creating a controlled input
import React, { useState } from 'react';

function ControlledInput() {
    const [value, setValue] = useState('');

    const handleChange = (event) => {
        setValue(event.target.value);
    };

    return (
        <div>
            <input type="text" value={value} onChange={handleChange} />
            <p>Input value: {value}</p>
        </div>
    );
}

export default ControlledInput;

Handling Multiple Inputs

To handle multiple inputs in a form, you can use a single state object to store the values of all inputs and update the state based on the input name.

// Handling multiple inputs
import React, { useState } from 'react';

function ControlledForm() {
    const [formValues, setFormValues] = useState({
        username: '',
        email: ''
    });

    const handleChange = (event) => {
        const { name, value } = event.target;
        setFormValues({
            ...formValues,
            [name]: value
        });
    };

    return (
        <form>
            <div>
                <label>
                    Username:
                    <input type="text" name="username" value={formValues.username} onChange={handleChange} />
                </label>
            </div>
            <div>
                <label>
                    Email:
                    <input type="email" name="email" value={formValues.email} onChange={handleChange} />
                </label>
            </div>
            <p>Username: {formValues.username}</p>
            <p>Email: {formValues.email}</p>
        </form>
    );
}

export default ControlledForm;

Handling Form Submission

To handle form submission, you need to define an onSubmit handler that prevents the default form submission behavior and processes the form data.

// Handling form submission
import React, { useState } from 'react';

function ControlledForm() {
    const [formValues, setFormValues] = useState({
        username: '',
        email: ''
    });

    const handleChange = (event) => {
        const { name, value } = event.target;
        setFormValues({
            ...formValues,
            [name]: value
        });
    };

    const handleSubmit = (event) => {
        event.preventDefault();
        // Process form data
        console.log('Form submitted:', formValues);
    };

    return (
        <form onSubmit={handleSubmit}>
            <div>
                <label>
                    Username:
                    <input type="text" name="username" value={formValues.username} onChange={handleChange} />
                </label>
            </div>
            <div>
                <label>
                    Email:
                    <input type="email" name="email" value={formValues.email} onChange={handleChange} />
                </label>
            </div>
            <button type="submit">Submit</button>
        </form>
    );
}

export default ControlledForm;

Full Example

Here is a complete example of a form managed with controlled components in a React application:

// App.js
import React, { useState } from 'react';

function App() {
    const [formValues, setFormValues] = useState({
        username: '',
        email: ''
    });

    const handleChange = (event) => {
        const { name, value } = event.target;
        setFormValues({
            ...formValues,
            [name]: value
        });
    };

    const handleSubmit = (event) => {
        event.preventDefault();
        // Process form data
        console.log('Form submitted:', formValues);
    };

    return (
        <div className="container">
            <h1>Controlled Components in React</h1>
            <form onSubmit={handleSubmit}>
                <div>
                    <label>
                        Username:
                        <input type="text" name="username" value={formValues.username} onChange={handleChange} />
                    </label>
                </div>
                <div>
                    <label>
                        Email:
                        <input type="email" name="email" value={formValues.email} onChange={handleChange} />
                    </label>
                </div>
                <button type="submit">Submit</button>
            </form>
            <p>Form Values: {JSON.stringify(formValues)}</p>
        </div>
    );
}

export default App;

Summary

In this tutorial, you learned how to manage forms with controlled components in React. Controlled components are form elements whose values are controlled by React state, providing a single source of truth for form data. You learned how to create controlled inputs, handle multiple inputs, and manage form submission. Understanding controlled components is essential for writing robust and maintainable forms in React applications.