Sage-Code Laboratory
index<--

Chapter 9: Working with Forms in React

Chapter 9 delves into creating and handling forms in React applications. Forms allow users to interact with your application by providing input, and React provides mechanisms to manage this user interaction effectively.

Handling Form Submissions in React

Unlike traditional HTML forms that submit data directly to the server, forms in React applications typically handle submissions using JavaScript within the component itself. This allows you to control the submission process, validate user input, and update the application state accordingly.

Here's a basic example of handling form submission in React:


import React, { useState } from 'react';

function ContactForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');

const handleSubmit = (event) => {
    event.preventDefault(); // Prevent default form submission behavior
    console.log('Form submitted!', { name, email });
    // Here, you can perform additional actions like sending data to an API
    setName('');
    setEmail('');
};

return (
    <form onSubmit={handleSubmit}>
    <label htmlFor="name">Name: </label>
    <input type="text" id="name" value={name} onChange={(e) => setName(e.target.value)} />
    <label htmlFor="email">Email: </label>
    <input type="email" id="email" value={email} onChange={(e) => setEmail(e.target.value)} />
    <button type="submit">Submit </button>
    </form >
);
}

In this example:

Controlled Components for Form Inputs

In React, forms are typically implemented using controlled components. This means the form data is controlled by the React component's state, rather than by the DOM itself. This approach allows for better control over the form's behavior and validation.

Here, the input fields have a "value" attribute set to the corresponding state variable ("name" or "email"). This ensures the displayed value in the input reflects the current state. The "onChange" handler updates the state whenever the user modifies the input, maintaining consistency between the UI and the component's state.

Validating User Input

Validating user input is crucial to ensure the integrity of your application's data. React allows you to implement validation logic to check if the entered data meets specific criteria before submission.

Here are some common validation techniques:

Regular Expressions

You can use regular expressions to validate specific input formats, such as email addresses, phone numbers, or passwords. Libraries like "react-hook-form" or custom validation functions can help with this process.

Example of Inline Validation:

import React, { useState } from 'react';

function RegistrationForm() {
    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
    const [errorMessage, setErrorMessage] = useState('');

    const validateEmail = (email) => {
    const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(String(email).toLowerCase());
    };

    const handleChange = (event) => {
        const { name, value } = event.target;
        if (name === 'email') {
            setErrorMessage(validateEmail(value) ? '' : 'Please enter a valid email address');
        }
        // Update state for name or email based on event.target
    };

    const handleSubmit = (event) => {
        event.preventDefault();
        // Perform form submission logic
    };

    return (
        <form onSubmit={handleSubmit}>
            <label htmlFor="name">Name:</label>
            <input type="text" id="name" value={name} onChange={handleChange} />
            <label htmlFor="email">Email:</label>
            <input type="email" id="email" value={email} onChange={handleChange} />
            <span style={{ color: 'red' }}>{errorMessage}</span>
            <button type="submit">Register</button>
        </form>
    );
}

Read next: Fatching Data