React Forms and User Input

📘 React.js 👁 40 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

React forms are used to collect user input and manage it using state. React typically uses controlled components, where form data is handled by React state.


Controlled Components

A controlled component means the input value is controlled by React state.

import { useState } from "react"; function LoginForm() { const [username, setUsername] = useState(""); return ( <input type="text" value={username} onChange={e => setUsername(e.target.value)} /> ); }

Handling Multiple Inputs

Use one state object and update fields dynamically.

function RegisterForm() { const [form, setForm] = useState({ name: "", email: "" }); function handleChange(e) { setForm({ ...form, [e.target.name]: e.target.value }); } return ( <> <input name="name" value={form.name} onChange={handleChange} /> <input name="email" value={form.email} onChange={handleChange} /> </> ); }

Handling Form Submission

function Form() { function handleSubmit(e) { e.preventDefault(); console.log("Form submitted"); } return ( <form onSubmit={handleSubmit}> <button type="submit">Submit</button> </form> ); }

Textarea and Select

Textarea

<textarea value={message} onChange={e => setMessage(e.target.value)} />

Select

<select value={role} onChange={e => setRole(e.target.value)} > <option value="user">User</option> <option value="admin">Admin</option> </select>

Checkbox and Radio Buttons

Checkbox

<input type="checkbox" checked={isChecked} onChange={e => setIsChecked(e.target.checked)} />

Radio

<input type="radio" value="male" checked={gender === "male"} onChange={e => setGender(e.target.value)} />

Basic Validation Example

function Login() { const [email, setEmail] = useState(""); function handleSubmit(e) { e.preventDefault(); if (!email) { alert("Email is required"); } } return ( <form onSubmit={handleSubmit}> <input type="email" value={email} onChange={e => setEmail(e.target.value)} /> <button>Submit</button> </form> ); }

Uncontrolled Components (Optional)

Using ref instead of state.

const inputRef = React.useRef(); <input ref={inputRef} />

Used rarely; controlled components are preferred.


Best Practices

  • Use controlled components

  • Handle submit with onSubmit

  • Validate inputs

  • Keep form logic organized


Key Points

  • React forms use state

  • Inputs update state via onChange

  • Form submission uses onSubmit

  • Controlled components are recommended


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes