Home
← All questions

Implement a reusable form field component with validation in React

MediumPremiumReact

React interview practice: Design a controlled, reusable input field component with validation and error display.

Problem

Build a reusable <FormField> that handles label, value, change, blur, and validation error display. Show how to compose it into a form.

Approach / Solution

// FormField.jsx
function FormField({ label, name, value, onChange, onBlur, error, type = "text" }) {
  return (
    <div className="field">
      <label htmlFor={name}>{label}</label>
      <input
        id={name}
        name={name}
        type={type}
        value={value}
        onChange={(e) => onChange(name, e.target.value)}
        onBlur={() => onBlur(name)}
        aria-invalid={!!error}
      />
      {error && <span className="error">{error}</span>}
    </div>
  );
}

// Usage with a tiny validation hook
function useForm(initial, validators) {
  const [values, setValues] = React.useState(initial);
  const [errors, setErrors] = React.useState({});
  const onChange = (name, val) => setValues((v) => ({ ...v, [name]: val }));
  const validate = (name) =>
    setErrors((e) => ({ ...e, [name]: validators[name]?.(values[name]) }));
  return { values, errors, onChange, onBlur: validate };
}

Discussion points: controlled vs uncontrolled, validating on blur vs submit, schema validation (Zod/Yup), and accessibility (aria-invalid, label association). In production, prefer react-hook-form for performance (uncontrolled inputs, fewer re-renders).

Premium question

Unlock the full model answer with Mentoxis Premium.

Unlock with Premium