Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Machine Coding Patterns
  1. 1.Setting Up for Machine Coding
  2. 2.Interactive UI Basics: Counter & Toggle
  3. 3.Building a Static Component: Star Rating
  4. 4.Handling User Input: Form Elements
  5. 5.Displaying Dynamic Data: Todo List
  6. 6.Filtering & Searching Data
  7. 7.Pagination & Infinite Scroll
  8. 8.Advanced UI Components: Modals & Tooltips
  9. 9.Drag & Drop Functionality (Basic)
  10. 10.Reusability Patterns: Hooks & HOCs
  11. 11.Performance Optimization Techniques
  12. 12.Complex State Management & Architecture
Machine Coding Patterns
04

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.

  1. Your component's state dictates the value (or checked) prop of the input element.
  2. The user interacts with the input, triggering an onChange event.
  3. The event handler updates the component's state with the new value.
  4. The component re-renders, passing the updated state back to the input's value prop.

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 onSubmit on the form instead of onClick on the button?"

You: "Using onSubmit is better for accessibility and standard browser behavior. It allows users to submit the form by pressing the Enter key in an input field, which an onClick on 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.

Try a free mock interviewPractice machine coding problems
Previous

Building a Static Component: Star Rating

Next

Displaying Dynamic Data: Todo List