Loading content…
Loading content…
Build a React login form containing email and password inputs using controlled state components. Enforce form validations: show validation errors when leaving the field (onBlur) if entries are invalid.
Expected Output
A form component rendering input boxes, validation status text, and disabling submit buttons when inputs are invalid.
Click to toggle the recommended code solution
Architectural Explanation
The component binds inputs to React states, tracks field interaction states inside a touched object, validates values dynamically on render, and displays accessible feedback text.Code Snippet
import React, { useState } from "react";
export function ControlledForm() {
const [email, setEmail] = useState("");
const [touched, setTouched] = useState({ email: false });
const emailError = touched.email && !email.includes("@") ? "Invalid email address" : null;
return (
<form onSubmit={e => e.preventDefault()} class="space-y-4">
<div>
<label for="email" class="block text-xs font-bold uppercase text-slate-500">Email</label>
<input
id="email"
type="email"
value={email}
onBlur={() => setTouched({ ...touched, email: true })}
onChange={e => setEmail(e.target.value)}
class={`border p-2 rounded w-full ${emailError ? "border-red-500" : "border-slate-300"}`}
/>
{emailError && <p class="text-xs text-red-500 mt-1">{emailError}</p>}
</div>
<button type="submit" disabled={!!emailError || !email} class="bg-indigo-600 text-white px-4 py-2 rounded disabled:opacity-50">
Log In
</button>
</form>
);
}How to pitch this solution during technical interviews
I configure forms using controlled elements. State controls input variables, and validation runs during render loops. I track blurred parameters inside a touched state to prevent validation alerts from rendering before a user types.