Machine Coding · Lesson 4 of 12 · 3 min
Handling User Input: Form Elements
This is the default pattern for forms in interviews. Getting it wrong is a major red flag.
After this lesson, you'll be able to implement any form using the single pattern interviewers expect to see. This pattern ensures your UI and state are always in sync, which is the foundation for validation, real-time feedback, and complex form logic.
Why Controlled Components are the Default
In a controlled component, the component's state is the single source of truth for the input element's value. The React (or Vue, or Svelte) state "controls" the input.
The alternative is an uncontrolled component, where the DOM manages the input's state internally. You might query the DOM for the value on submit. Don't do this in an interview unless you have a specific, justifiable reason (like integrating a non-React library or managing file inputs).
Controlled components make implementing instant validation, conditional logic (disabling a button until a field is filled), or dynamic formatting (like for a phone number) trivial. With uncontrolled components, it's a mess of DOM refs and manual checks. Stick to controlled.
The Data Flow: State → UI → State
The flow is a simple, predictable loop.
- Your component's state dictates the
value(orchecked) prop of the input element. - The user interacts with the input, triggering an
onChangeevent. - The event handler updates the component's state with the new value.
- The component re-renders, passing the updated state back to the input's
valueprop.
The DOM never holds the "true" state. It only reflects what your component's state tells it to.
The trap: If you provide a value prop to an input without an onChange handler, React will render a read-only element. The user won't be able to type in it. This is a common mistake that silently breaks your UI. If you see an input you can't type in, you've likely made this error.
Implementing a Generic Handler for Multiple Inputs
You don't need a separate state and handler for every input. For any form with more than one field, use a single state object and a generic handler. This is the pattern to show in an interview.
The key is to use the name attribute on each input. Make it match the corresponding key in your state object. The generic handler can then use event.target.name to update the correct piece of state.
Notice how the handler also checks event.target.type to correctly get the value from either checked (for checkboxes) or value (for everything else).
import React, { useState } from 'react';
function RegistrationForm() {
const [formData, setFormData] = useState({
username: '',
email: '',
newsletter: false,
});
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { name, value, type, checked } = event.target;
setFormData(prevData => ({
...prevData,
[name]: type === 'checkbox' ? checked : value,
}));
};
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
console.log('Form submitted:', formData);
// API call would go here
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="username">Username:</label>
<input
id="username"
type="text"
name="username"
value={formData.username}
onChange={handleChange}
/>
</div>
<div>
<label htmlFor="newsletter">Subscribe to newsletter:</label>
<input
id="newsletter"
type="checkbox"
name="newsletter"
checked={formData.newsletter}
onChange={handleChange}
/>
</div>
<button type="submit">Register</button>
</form>
);
}
Handling Form Submission
Always wrap your inputs in a <form> element and handle submission with the form's onSubmit event, not the button's onClick.
Interviewer: "Why use
onSubmiton the form instead ofonClickon the button?"You: "Using
onSubmitis better for accessibility and standard browser behavior. It allows users to submit the form by pressing the Enter key in an input field, which anonClickon a button doesn't handle by default. It's the semantically correct way to handle form submissions."
The first line of your handleSubmit function must always be event.preventDefault(). Always. Forgetting this causes the browser to perform a default form submission, which means a full page reload. In a single-page application, this wipes your state and breaks the app.
The trap: Forgetting event.preventDefault() is an instant failure in a machine coding round. Your app will visibly break the moment the interviewer tries to submit the form.
Try it
Build a temperature converter. Create two text inputs: one for Celsius and one for Fahrenheit. When you type a number in one input, the other input should update in real-time with the converted value. This will test your understanding of a two-way controlled component flow.
Next: Displaying Dynamic Data: Todo List
Lock it in — apply this lesson under interview conditions.