DEV Community

Ujjwal Sinha
Ujjwal Sinha

Posted on

Handle Form State in React

Handle Form State in React is used to update the state of a component when the user interacts with an input field (e.g., typing in a text box, selecting an option, etc.). It is a fundamental part of handling form inputs in React.

Let’s break down how it works, its use cases, and how you can extend it to perform specific actions (like when the user is on the mobile_number field).

How Input Change Handler Works

1. Event Object:

  • When the user types in an input field, an onChange event is triggered.

  • This event contains information about the input field, such as its name and value.

2. Updating State:

  • The input change handler extracts the name and value from the event object.

  • It then updates the corresponding state property using the setState function.

3. Dynamic State Updates:

  • By using the name attribute of the input field, the handler can dynamically update the correct property in the state object.

Basic Input Change Handler

Here’s a simple example of an input change handler:

const handleInputChange = (e) => {
  const { name, value } = e.target; // Extract name and value from the event
  setFormState({
    ...formState, // Spread the existing state
    [name]: value // Update the specific field
  });
};
Enter fullscreen mode Exit fullscreen mode

Use Cases for Input Change Handler

1. Form Handling:

  • Update form state as the user types in input fields.

  • Enable/disable buttons or show/hide elements based on form state.

2. Validation:

  • Perform real-time validation (e.g., check if an email is valid or if a password meets requirements).

3. Dynamic Behavior:

  • Trigger specific actions when the user interacts with a particular field (e.g., auto-format a phone number or show suggestions).

4. Conditional Rendering:

  • Show or hide additional fields based on user input.

Advanced Use Case: Perform Actions Based on the Active Field

If you want to perform specific actions when the user is interacting with a particular field (e.g., mobile_number), you can extend the input change handler to include conditional logic.

Example: Auto-Format Mobile Number

const handleInputChange = (e) => {
  const { name, value } = e.target;

  // Perform specific actions based on the field name
  if (name === 'mobile_number') {
    // Auto-format mobile number (e.g., add dashes)
    const formattedValue = value.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
    setFormState({
      ...formState,
      [name]: formattedValue
    });
  } else {
    // Update other fields normally
    setFormState({
      ...formState,
      [name]: value
    });
  }
};
Enter fullscreen mode Exit fullscreen mode

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay