Lesson 1 - Setup a Simple Form and Input

All About React Form

What is a Form in React?

A form in React is a web interface component that allows users to input data that can then be processed by a web application. Common examples include login forms, sign-up forms, and contact forms

In React, forms are built using HTML form elements like <input>, <textarea>, <button><select>, etc., just like in traditional HTML. However, React provides a way to manage form data and handle user interactions within your component state.

React forms leverage the framework's ability to maintain application state and handle user inputs efficiently. By combining these forms with React’s state and event-handling features, developers can create interactive and controlled user interfaces.

Key Concepts

  • Controlled Components: In React, form elements are typically "controlled" components. This means their values are managed by the component's state. The component's state dictates what the user sees in the input fields.

  • preventDefault():

    • The preventDefault method is a JavaScript function available in browser events that stops the default behavior of an event.

    • When a form is submitted, the browser by default performs a page refresh.

    • To prevent this default behavior and handle the form submission within your React component, you use the preventDefault() method on the onSubmit event of the form.

    • This allows you to capture the form data and perform any necessary actions (e.g., making API calls, updating state) before the page reloads.

// Example of preventDefault
function handleSubmit(event) {
  event.preventDefault(); // Prevents the form from reloading the page
  console.log("Form submitted!");
}

return (
  <form onSubmit={handleSubmit}>
    <input type="text" placeholder="Enter your name" />
    <button type="submit">Submit</button>
  </form>
);

How to Use Forms for Input, Button Click, and Controlled Elements

1. Input Handling

Inputs in React can be managed using two main approaches: controlled and uncontrolled components.

  • Controlled Components: In a controlled component, the form data is handled by React state. The value of an input is set by a state variable, and the onChange event updates the state. This ensures React has full control over the form input.

Example of Controlled Input:

JavaScript(XML)

import React, { useState } from 'react';

function ControlledForm() {
  const [username, setUsername] = useState('');

  const handleSubmit = (event) => {
    event.preventDefault(); // Prevent default form submission

    // Process the form data (e.g., send it to a server)
    //setUserName(event.target.value)
    console.log('Username:', username); 
  };

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="username">Username:</label>
      <input
        type="text"
        id="username"
        value={username} // Controlled input - value comes from state
        onChange={(event) => setUsername(event.target.value)} 
      />
      <button type="submit">Submit</button>
    </form>
  );
}

export default ControlledForm;

Explanation

  1. State Management: The username state variable is used to store the current value of the input field.

  2. Controlled Input: The value of the input field is linked to the username state using the value attribute. This ensures that the input field always reflects the current state of the component.

  3. onChange Handler: The onChange event handler updates the username state whenever the user types in the input field. This keeps the component's state in sync with the user's input.

  4. onSubmit Handler: The handleSubmit function is called when the form is submitted.

    • event.preventDefault() is used to prevent the default form submission behavior.

    • The function then processes the form data (in this case, simply logging the username to the console).

Key Points

  • Forms in React are typically controlled components, meaning their values are managed by the component's state.

  • The preventDefault() method is essential for handling form submissions within React components.

  • By using state and event handlers, you can create interactive forms that respond to user input and perform actions accordingly.

  • Uncontrolled Components: Uncontrolled components use refs to access the DOM elements directly, instead of relying on state. This approach is less common in React but can be useful in certain scenarios.

Example of Uncontrolled Input:

import React, { useRef } from 'react';

function UncontrolledForm() {
  const inputRef = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(inputRef.current.value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" ref={inputRef} placeholder="Enter your name" />
      <button type="submit">Submit</button>
    </form>
  );
}

Controlling Form Elements

To control form elements in React, you need to:

  1. Bind the value of the input to a state variable.

  2. Update the state variable using an onChange handler.

Example of Multiple Controlled Inputs:

function MultiInputForm() {
  const [formData, setFormData] = useState({
    email: "",
    password: "",
  });

  const handleChange = (event) => {
    const { name, value } = event.target;
    setFormData((prevData) => ({ //set input filed data one by one
      ...prevData,
      [name]: value,
    }));
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(formData);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        name="email"
        value={formData.email}
        onChange={handleChange}
        placeholder="Enter your email"
      />
      <input
        type="password"
        name="password"
        value={formData.password}
        onChange={handleChange}
        placeholder="Enter your password"
      />
      <button type="submit">Submit</button>
    </form>
  );
}

Code Explanation

State Management:

  • The component uses the useState hook to manage the form data. It creates a state object called formData with two properties: email (initially an empty string) and password (initially an empty string).

Input Handling:

  • The handleChange function is responsible for handling changes in the input fields. It's triggered whenever the user types in either the email or password field.

    • It destructures the event.target object to access the name (which corresponds to the input field's name attribute) and the value (the entered text).

    • It uses the setFormData function to update the state. The updated state is created using a callback function that receives the previous state (prevData). This ensures you don't accidentally overwrite other form data properties.

    • Inside the callback function, it spreads the previous state (...prevData) to create a copy, and then updates the specific property ([name]) with the new value.

Form Submission:

  • The handleSubmit function handles form submission when the user clicks the "Submit" button.

    • It prevents the default form submission behavior using event.preventDefault().

    • In a real application, you would typically make an API call to submit the form data to a server or perform some other action. Here, it simply logs the current state (formData) to the console for demonstration purposes.

Summary

Forms in React are powerful tools for building interactive user interfaces. By using React’s state management and event-handling capabilities, developers can create highly responsive and user-friendly forms. Key concepts like controlled components, preventDefault, and handling inputs and buttons effectively enable developers to implement robust form features in their applications.

Last updated