Handling Form Inputs in React

๐Ÿ“ Handling Form Inputs in React (English)

React makes handling form inputs straightforward with controlled components. Here's a complete guide to help you handle form inputs effectively using modern React practices.


✅ 1. What Are Controlled Components?

A controlled component is a form input element whose value is controlled by React state.


Example:


jsx

Copy

Edit

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

๐Ÿ› ️ 2. Basic Form Example

Here’s how to handle a simple form with name and email fields:


✅ Functional Component with Hooks

jsx

Copy

Edit

import React, { useState } from 'react';


function ContactForm() {

  const [formData, setFormData] = useState({

    name: '',

    email: ''

  });


  const handleChange = (e) => {

    const { name, value } = e.target;

    setFormData(prev => ({

      ...prev,

      [name]: value

    }));

  };


  const handleSubmit = (e) => {

    e.preventDefault();

    console.log('Form submitted:', formData);

  };


  return (

    <form onSubmit={handleSubmit}>

      <label>

        Name:

        <input name="name" value={formData.name} onChange={handleChange} />

      </label>

      <br />

      <label>

        Email:

        <input name="email" value={formData.email} onChange={handleChange} />

      </label>

      <br />

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

    </form>

  );

}

๐Ÿ“‘ 3. Handling Different Input Types

a. Text Input

jsx

Copy

Edit

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

b. Checkbox

jsx

Copy

Edit

<input

  type="checkbox"

  name="subscribe"

  checked={formData.subscribe}

  onChange={(e) =>

    setFormData(prev => ({ ...prev, subscribe: e.target.checked }))

  }

/>

c. Radio Buttons

jsx

Copy

Edit

<input

  type="radio"

  name="gender"

  value="male"

  checked={formData.gender === 'male'}

  onChange={handleChange}

/>

<input

  type="radio"

  name="gender"

  value="female"

  checked={formData.gender === 'female'}

  onChange={handleChange}

/>

d. Select Dropdown

jsx

Copy

Edit

<select name="country" value={formData.country} onChange={handleChange}>

  <option value="">Select</option>

  <option value="US">United States</option>

  <option value="CA">Canada</option>

</select>

๐Ÿงผ 4. Validation Example

Basic example:


jsx

Copy

Edit

const handleSubmit = (e) => {

  e.preventDefault();

  if (!formData.email.includes('@')) {

    alert('Invalid email');

    return;

  }

  console.log('Form is valid:', formData);

};

For more advanced validation, consider libraries like:


Formik


react-hook-form


Yup (for schema validation)


๐Ÿ” 5. Two-Way Binding

In React, binding form inputs to state (and updating state on change) enables two-way binding.


jsx

Copy

Edit

<input

  type="text"

  name="username"

  value={formData.username}

  onChange={handleChange}

/>

Here, the input value is always synced with formData.username.


๐Ÿ“ฆ Summary

Feature Best Practice

Text inputs Use value + onChange

Checkboxes Use checked for Boolean

Form submission Use e.preventDefault()

Validation Manual or with a library

Controlled components Always bind to state

Learn React JS Course in Hyderabad

Read More

Building a Theme Toggler with useContext

How to Use useLayoutEffect Effectively

Visit Our Quality Thought Training in Hyderabad

Get Directions 

Comments

Popular posts from this blog

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Why Data Science Course?

How To Do Medical Coding Course?