Bird
Raised Fist0
Reactframework~5 mins

Form handling in React

Choose your learning style10 modes available
Introduction

Forms let users send information to your app. Handling forms in React helps you control what users type and respond to it easily.

When you want to collect user input like names or emails.
When you need to update the app as the user types.
When you want to check if the input is correct before sending it.
When you want to show messages or errors based on user input.
When you want to clear or reset the form after submission.
Syntax
React
function MyForm() {
  const [value, setValue] = React.useState('');

  function handleChange(event) {
    setValue(event.target.value);
  }

  function handleSubmit(event) {
    event.preventDefault();
    alert(`You typed: ${value}`);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="inputId">Enter text:</label>
      <input
        id="inputId"
        type="text"
        value={value}
        onChange={handleChange}
        aria-label="Text input"
      />
      <button type="submit">Submit</button>
    </form>
  );
}

Use useState to keep track of input values.

Use event.preventDefault() in submit handler to stop page reload.

Examples
Simple text input controlled by React state.
React
const [name, setName] = React.useState('');

<input
  type="text"
  value={name}
  onChange={e => setName(e.target.value)}
  aria-label="Name input"
/>
Form with submit handler that logs input value and prevents page reload.
React
<form onSubmit={e => {
  e.preventDefault();
  console.log('Submitted:', name);
}}>
  <input
    type="text"
    value={name}
    onChange={e => setName(e.target.value)}
    aria-label="Name input"
  />
  <button type="submit">Send</button>
</form>
Checkbox input controlled by React state.
React
const [checked, setChecked] = React.useState(false);

<input
  type="checkbox"
  checked={checked}
  onChange={e => setChecked(e.target.checked)}
  aria-label="Accept terms"
/>
Sample Program

This React component shows a simple email subscription form. It updates the input as you type, prevents page reload on submit, shows a thank you message, and clears the input.

React
import React from 'react';

export default function SimpleForm() {
  const [email, setEmail] = React.useState('');
  const [message, setMessage] = React.useState('');

  function handleChange(event) {
    setEmail(event.target.value);
  }

  function handleSubmit(event) {
    event.preventDefault();
    setMessage(`Thanks for submitting: ${email}`);
    setEmail('');
  }

  return (
    <main>
      <h1>Subscribe to newsletter</h1>
      <form onSubmit={handleSubmit} aria-label="Subscription form">
        <label htmlFor="emailInput">Email:</label>
        <input
          id="emailInput"
          type="email"
          value={email}
          onChange={handleChange}
          required
          aria-required="true"
          aria-describedby="msg"
        />
        <button type="submit">Subscribe</button>
      </form>
      <p id="msg" role="status" aria-live="polite">{message}</p>
    </main>
  );
}
OutputSuccess
Important Notes

Always add aria-label or label for accessibility.

Use required attribute to make inputs mandatory.

Clear input after submit to improve user experience.

Summary

React forms use state to control input values.

Use event handlers to update state and handle submit.

Accessibility and preventing page reload are important.

Practice

(1/5)
1. What is the main purpose of using useState in React form handling?
easy
A. To automatically validate form inputs
B. To style the form elements dynamically
C. To send form data directly to the server
D. To store and update the current value of form inputs

Solution

  1. Step 1: Understand useState role in React

    useState is used to create a state variable that holds data and can be updated.
  2. Step 2: Connect useState to form inputs

    In form handling, useState stores the current input value and updates it on user typing.
  3. Final Answer:

    To store and update the current value of form inputs -> Option D
  4. Quick Check:

    useState manages input values = A [OK]
Hint: useState holds input values and updates on change [OK]
Common Mistakes:
  • Thinking useState styles elements
  • Assuming useState sends data to server
  • Confusing useState with validation logic
2. Which of the following is the correct way to update state on input change in React?
easy
A. onChange={(e) => setValue(e.target.value)}
B. onChange={() => setValue(e.value)}
C. onChange={(e) => setValue(e.target)}
D. onChange={(e) => setValue(e.currentTarget)}

Solution

  1. Step 1: Identify correct event target usage

    The input value is accessed via e.target.value in event handlers.
  2. Step 2: Confirm correct syntax for setState call

    Using setValue(e.target.value) updates state with the input's current value.
  3. Final Answer:

    onChange={(e) => setValue(e.target.value)} -> Option A
  4. Quick Check:

    Use e.target.value to get input value [OK]
Hint: Use e.target.value inside onChange to update state [OK]
Common Mistakes:
  • Using e.value instead of e.target.value
  • Passing e.target or e.currentTarget directly
  • Omitting the event parameter e
3. What will be the output when the following React component is rendered and the user types 'Hi' in the input?
function GreetingForm() {
  const [name, setName] = React.useState('');
  return (
    <form>
      <input value={name} onChange={e => setName(e.target.value)} />
      <p>Hello, {name}!</p>
    </form>
  );
}
medium
A. The page reloads on typing
B. The paragraph shows 'Hello, Hi!' as user types 'Hi'
C. The paragraph remains empty regardless of input
D. The input clears automatically after typing

Solution

  1. Step 1: Understand controlled input behavior

    The input value is controlled by state variable 'name' which updates on change.
  2. Step 2: Observe paragraph rendering with state

    The paragraph displays 'Hello, {name}!' so it updates live as 'name' changes.
  3. Final Answer:

    The paragraph shows 'Hello, Hi!' as user types 'Hi' -> Option B
  4. Quick Check:

    Controlled input updates state and display = D [OK]
Hint: Controlled inputs update state and display live [OK]
Common Mistakes:
  • Expecting input to clear automatically
  • Thinking paragraph won't update
  • Assuming page reloads on input change
4. Identify the error in this React form submission handler:
function handleSubmit(e) {
  alert('Submitted');
}

What is missing to prevent the page from reloading on submit?
medium
A. Call e.preventDefault() inside handleSubmit
B. Use return false at the end of handleSubmit
C. Wrap alert in a setTimeout function
D. No error, the code works fine

Solution

  1. Step 1: Understand default form submit behavior

    By default, form submission reloads the page unless prevented.
  2. Step 2: Prevent default reload in React

    Calling e.preventDefault() inside the submit handler stops the reload.
  3. Final Answer:

    Call e.preventDefault() inside handleSubmit -> Option A
  4. Quick Check:

    Use e.preventDefault() to stop reload [OK]
Hint: Always call e.preventDefault() in submit handlers [OK]
Common Mistakes:
  • Forgetting to pass event parameter e
  • Using return false instead of preventDefault
  • Assuming alert stops reload
5. You want to handle multiple input fields in one React form using a single state object. Which code snippet correctly updates the state for the changed input field?
const [formData, setFormData] = React.useState({ email: '', password: '' });

function handleChange(e) {
  // What goes here?
}
hard
A. setFormData({ e.target.name: e.target.value });
B. setFormData({ formData[e.target.name]: e.target.value });
C. setFormData({ ...formData, [e.target.name]: e.target.value });
D. setFormData({ [e.target.value]: e.target.name });

Solution

  1. Step 1: Understand updating nested state objects

    To update one field in an object state, copy existing fields with spread operator.
  2. Step 2: Use computed property name for dynamic key

    Use [e.target.name] to dynamically update the correct field with new value.
  3. Final Answer:

    setFormData({ ...formData, [e.target.name]: e.target.value }); -> Option C
  4. Quick Check:

    Spread old state + dynamic key update = B [OK]
Hint: Use spread and [e.target.name] to update form object state [OK]
Common Mistakes:
  • Overwriting entire state without spreading
  • Using invalid object key syntax
  • Swapping name and value in update
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard