💻Lecture Notes Of Class 9: Forms in React

Rashmi Mishra
0

 💻Lecture Notes Of Class 9

 Forms in React


Objective:

  • Understand how to handle form input and submission in React.
  • Learn about controlled components.
  • Work with different form elements like input, textarea, and select.
  • Create a registration form and display submitted values.
  • Practice adding validation for required fields.

1. Introduction to Forms in React

In web applications, forms are used to collect user input like names, emails, passwords, and other information. React makes it easy to handle forms using controlled components — components that control the form elements through React state.


2. What is a Controlled Component?

  • A controlled component is an input form element whose value is controlled by React.
  • Instead of the input element maintaining its own state, React state holds the value, and the input reflects the React state.
  • This means every time a user types something, React updates the state, and React re-renders the input with the updated value.

Why use controlled components?

  • To manage the form data within React.
  • To validate and manipulate input easily.
  • To keep React as the "single source of truth" for the form data.

3. Form Elements in React

a. Input (Text, Email, Password, etc.)

import React, { useState } from 'react'; 

function TextInputExample() {

  const [name, setName] = useState('');

 

  const handleChange = (event) => {

    setName(event.target.value);

  };

 

  return (

    <input type="text" value={name} onChange={handleChange} />

  );

}

Explanation:

  • value={name} binds the input value to React state.
  • onChange={handleChange} updates state when user types.

b. Textarea (Multi-line input)

const [description, setDescription] = useState(''); 

<textarea value={description} onChange={(e) => setDescription(e.target.value)} />


c. Select (Dropdown)

const [color, setColor] = useState('red'); 

<select value={color} onChange={(e) => setColor(e.target.value)}>

  <option value="red">Red</option>

  <option value="green">Green</option>

  <option value="blue">Blue</option>

</select>


4. Handling Form Submission

  • We use the onSubmit event handler on the <form> element.
  • Prevent the default form submission behavior using event.preventDefault() so the page doesn’t reload.
  • Use state to access form values and do something with them, like displaying or sending to a server.

Example:

function RegistrationForm() {

  const [name, setName] = useState('');

  const [email, setEmail] = useState('');

 

  const handleSubmit = (event) => {

    event.preventDefault();

    alert(`Name: ${name}, Email: ${email}`);

  };

 

  return (

    <form onSubmit={handleSubmit}>

      <input

        type="text"

        placeholder="Name"

        value={name}

        onChange={(e) => setName(e.target.value)}

      />

      <input

        type="email"

        placeholder="Email"

        value={email}

        onChange={(e) => setEmail(e.target.value)}

      />

      <button type="submit">Register</button>

    </form>

  );

}


5. Complete Activity: Create a Registration Form

Features:

  • Fields: Name, Email, Password, Gender (select), Bio (textarea)
  • Display all input values on form submit below the form.

Sample Code:

import React, { useState } from 'react'; 

function RegistrationForm() {

  const [name, setName] = useState('');

  const [email, setEmail] = useState('');

  const [password, setPassword] = useState('');

  const [gender, setGender] = useState('male');

  const [bio, setBio] = useState('');

  const [submittedData, setSubmittedData] = useState(null);

 

  const handleSubmit = (e) => {

    e.preventDefault();

    setSubmittedData({ name, email, password, gender, bio });

  };

 

  return (

    <div>

      <form onSubmit={handleSubmit}>

        <input

          type="text"

          placeholder="Name"

          value={name}

          onChange={(e) => setName(e.target.value)}

          required

        /><br/>

 

        <input

          type="email"

          placeholder="Email"

          value={email}

          onChange={(e) => setEmail(e.target.value)}

          required

        /><br/>

 

        <input

          type="password"

          placeholder="Password"

          value={password}

          onChange={(e) => setPassword(e.target.value)}

          required

        /><br/>

 

        <select value={gender} onChange={(e) => setGender(e.target.value)}>

          <option value="male">Male</option>

          <option value="female">Female</option>

          <option value="other">Other</option>

        </select><br/>

 

        <textarea

          placeholder="Bio"

          value={bio}

          onChange={(e) => setBio(e.target.value)}

        ></textarea><br/>

 

        <button type="submit">Register</button>

      </form>

 

      {submittedData && (

        <div>

          <h3>Submitted Data:</h3>

          <p>Name: {submittedData.name}</p>

          <p>Email: {submittedData.email}</p>

          <p>Password: {submittedData.password}</p>

          <p>Gender: {submittedData.gender}</p>

          <p>Bio: {submittedData.bio}</p>

        </div>

      )}

    </div>

  );

}

 

export default RegistrationForm;


6. Homework: Add Validation for Required Fields

  • Make sure Name, Email, and Password fields are required.
  • Show an error message if the user tries to submit the form without filling these fields.
  • Bonus: Validate that the email is in correct format.

Summary:

  • React forms use controlled components to manage input values.
  • Use useState hooks to store input values.
  • Handle input changes with onChange events.
  • Use onSubmit event on form to handle submission.
  • Display submitted data using React state.
  • Validation is important for better user experience.
Tags

Post a Comment

0Comments

Post a Comment (0)