ReactJS-The Beginner Master Class
  • React In the Beginning
    • Lesson 1 - Demo: Build a Simple React App - Fast
    • Lesson 2 - HTML Review
    • Lesson 3 - CSS Review
    • Lesson 4 - Modern JavaScript (JSX) Patterns
    • Lesson 5 - Set up Dev Environment
    • Hands-on Practice
  • React Fundamentals
    • Lesson 1 - Understanding Old vs New Way of Building Web Apps - SPAs
    • Lesson 2 - Motivation for Using React as the Solution to Vanilla JS
    • Lesson 3 - What is ReactJS - How it Works
    • React Code Along from Scratch
    • Lesson 4 - Create and Run a React Project with Vite - Full Overview
    • Lesson 5 - Create Hook by State Management in React
    • Lesson 6 - React Project File and Folder Walkthrough
    • Lesson 7 - JSX and How React Treats the DOM & JSX Compilation(by Babeljs) - Overview
    • Lesson 8 - Understanding the Main Files - App.jsx and main.jsx
    • Lesson 9 - Props and One-Way Data Flow - Overview
    • Lesson 10 - Google Bookshelf App - Ver 1.0
    • Hands-on Practice I
    • Hands-on Practice II
  • React State and Styling
    • Lesson 1 - Pulling Book Data from a Different Data File
    • Lesson 2 - Overview of How State Works in React
    • Lesson 3 - RandomQuote App
    • Lesson 4 - Lifting State Up - React Pattern Overview
    • Hands-On - Simple Counter
  • Forms and Interactivity - Grocery List App
    • Lesson 1 - Setup a Simple Form and Input
    • Lesson 2 - Build Form Profile App Using Multi-input Form Data
    • Hands-on : Build a Grocery List App
  • Connecting to the Backend - Consuming APIs - UseEffect Hook
    • Lesson 1 - Connecting to the Back End - Understanding Side Effects, Hooks and useEffect - Overview
    • Lesson 2 - Fetching Data from the Backend the Right Way with useEffect Hook
    • Lesson 3 - Setting Up Loading State
    • Hands-on :Use Dependency Array and Adding Values that Control Side Effects
  • Solo Project 1
  • RESTful APIs :Build a BookSearch App -Ver 2.0
    • Lesson 1: Build and test RESTful APIs with Postman
    • Lesson 2 - BookShelf App Structure
    • Lesson 3 - Create NavBar.jsx Component
    • Lesson 4 - Create Footer Component
    • Lesson 5 - Create BookList.jsx Component
    • Lesson 6 - Create BookCard.jsx Component
    • Lesson 7 - Creating Custom Hooks - useBooks and api-client
    • Lesson 8 - Controlling Network Activities in React with AbortController
    • Lesson 9 - Show Book Details in a Modal - Working
    • Lesson 10 - Bookshelf App Summary
  • Multi-Page Applications (MPAs)
    • Build a Multi-Page React Application
    • Multi-Page React Application
    • Hands-on Practice
  • Backend Frameworks-NEXT.JS
    • Migrating from React to Next.js
    • Lesson 1: Key Concepts of NodeJS and Express for Backend Web Development
    • Lesson 2: How to set up a new Next.js project
    • Lesson 3: How to create Layouts and Pages
    • Hands-on Practice 1
    • Hands on Practice 2
      • New Project & Folder Structure
      • File-Based Routing
      • Server vs Client Components & Router Hooks
      • Start On The Navbar
      • Navbar Links, Dropdowns & React Icons
      • Active Links & Conditional Rendering
      • Homepage Components
      • Properties Page
      • Property Card Dynamic Data
      • Home Property Listings
      • Custom Not Found & Loading Pages
  • Git and GitHubs
    • Git Installation
    • Git Commands
    • GitHub Repository
    • Hands-on Practice
  • Database in Application
    • React Supabase CRUD
    • Hands-on: Note Taking App
  • NoSQL Database
    • Installing MongoDB Community Edition
    • System Env Path Setting
    • How to use MongoDB Shell
    • How to Connect and Use Mongosh in VS Code via MongoDB Extension
    • MongoDB Guide
  • Solo Project 2
  • Deployment and Web Hosting
    • Lesson 1. React+Vite+TS+Shadcn Project
    • Lesson 2. Deploying a React Vite App to Vercel from Vercel CLI
    • Lesson 3 Connecting to GitHub Repo and Automate Deployment
  • Solo Project 3
  • Final Term Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 1 Team Project
    • Level 2 Team Project
    • Level 2 Team Project
    • Level 3 Team Project
    • Level 3 Team Project
Powered by GitBook
On this page
  • All About React Form
  • What is a Form in React?
  • How to Use Forms for Input, Button Click, and Controlled Elements
  • Controlling Form Elements
  • Code Explanation
  • Summary
  1. Forms and Interactivity - Grocery List App

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.

PreviousForms and Interactivity - Grocery List AppNextLesson 2 - Build Form Profile App Using Multi-input Form Data

Last updated 4 months ago