MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Custom Form Controls with useField0%
Study Materials
React.js for AdvancedProgress 0%
1.1Control Props and Inversion of Control Pattern1.2State Reducer Pattern in Advanced React1.3Prop Getters and Flexible Design Systems1.4Headless UI Architecture and Accessibility Primitives
12.1Formik Architecture and Field Arrays12.2Multi-Step Wizards and Dynamic Schema Validation with Yup12.3Custom Form Controls with useField12.4High-Performance Form Optimization Comparison
HomeTutorialsReact.js for AdvancedCustom Form Controls with useField
High-Performance Form Optimization Comparison

Custom Form Controls with useField

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Standard HTML <input> and <select> elements rarely satisfy enterprise UI standards. Design systems demand bespoke controls: custom multi-select tag pickers, star rating widgets, masked phone inputs, and toggle switches. Formik's useField hook connects arbitrary custom React components directly to Formik's validation and state engine.


1. Anatomy of useField

The useField hook accepts a field name (or props object) and returns a tuple containing three items:

1const [field, meta, helpers] = useField(name);
  • field: Props to spread onto standard inputs (name, value, onChange, onBlur).
  • meta: Metadata regarding field state (value, error, touched, initialValue).
  • helpers: Imperative setter functions (setValue, setTouched, setError) to update Formik state programmatically from custom UI events.

2. Building a Custom Switch Toggle Control

1import React from "react";
2import { useField } from "formik";
3 
4interface SwitchToggleProps {
5 name: string;
6 label: string;
7 description?: string;
8}
9 
10export function SwitchToggle({ name, label, description }: SwitchToggleProps) {
11 // Bind custom toggle directly to Formik
12 const [field, meta, helpers] = useField<boolean>(name);
13 
14 const isChecked = Boolean(field.value);
15 
16 const handleToggle = () => {
17 helpers.setValue(!isChecked);
18 helpers.setTouched(true);
19 };
20 
21 return (
22 <div className="flex items-center justify-between p-4 bg-slate-900 border border-slate-800 rounded-xl">
23 <div>
24 <label className="text-sm font-semibold text-white block">{label}</label>
25 {description && <p className="text-xs text-slate-400">{description}</p>}
26 {meta.touched && meta.error && (
27 <span className="text-xs text-rose-400 block mt-1">{meta.error}</span>
28 )}
29 </div>
30 
31 {/* Custom accessible switch primitive */}
32 <button
33 type="button"
34 role="switch"
35 aria-checked={isChecked}
36 onClick={handleToggle}
37 className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-cyan-500 ${
38 isChecked ? "bg-cyan-600" : "bg-slate-700"
39 }`}
40 >
41 <span
42 className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${
43 isChecked ? "translate-x-6" : "translate-x-1"
44 }`}
45 />
46 </button>
47 </div>
48 );
49}

3. Building a Multi-Select Tag Input

1import React, { useState } from "react";
2import { useField } from "formik";
3 
4interface TagInputProps {
5 name: string;
6 label: string;
7 placeholder?: string;
8}
9 
10export function TagInput({ name, label, placeholder = "Type and press Enter..." }: TagInputProps) {
11 const [field, meta, helpers] = useField<string[]>(name);
12 const [inputValue, setInputValue] = useState("");
13 
14 const tags = field.value || [];
15 
16 const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
17 if (e.key === "Enter" && inputValue.trim()) {
18 e.preventDefault();
19 if (!tags.includes(inputValue.trim())) {
20 helpers.setValue([...tags, inputValue.trim()]);
21 }
22 setInputValue("");
23 helpers.setTouched(true);
24 }
25 };
26 
27 const removeTag = (indexToRemove: number) => {
28 helpers.setValue(tags.filter((_, idx) => idx !== indexToRemove));
29 helpers.setTouched(true);
30 };
31 
32 return (
33 <div className="space-y-1">
34 <label className="block text-xs text-slate-400 font-medium">{label}</label>
35 
36 <div className="flex flex-wrap gap-2 p-2 bg-slate-900 border border-slate-800 rounded-lg min-h-[44px] items-center">
37 {tags.map((tag, idx) => (
38 <span
39 key={idx}
40 className="flex items-center gap-1 bg-cyan-950/60 text-cyan-300 border border-cyan-800 text-xs px-2.5 py-1 rounded-md"
41 >
42 {tag}
43 <button
44 type="button"
45 onClick={() => removeTag(idx)}
46 className="text-cyan-400 hover:text-white font-bold ml-1"
47 >
48 ×
49 </button>
50 </span>
51 ))}
52 
53 <input
54 type="text"
55 value={inputValue}
56 onChange={(e) => setInputValue(e.target.value)}
57 onKeyDown={handleKeyDown}
58 placeholder={tags.length === 0 ? placeholder : ""}
59 className="flex-1 bg-transparent text-sm text-white focus:outline-none min-w-[120px]"
60 />
61 </div>
62 
63 {meta.touched && meta.error && (
64 <div className="text-xs text-rose-400 mt-1">{meta.error}</div>
65 )}
66 </div>
67 );
68}

4. Seamless Formik Consumption

Because SwitchToggle and TagInput manage their own Formik subscriptions internally via useField, consuming them in forms is completely clean:

1<Formik initialValues={{ enable2FA: false, skillTags: ["React", "TypeScript"] }} onSubmit={...}>
2 <Form className="space-y-4">
3 <SwitchToggle
4 name="enable2FA"
5 label="Two-Factor Authentication"
6 description="Require TOTP hardware token on login"
7 />
8 <TagInput name="skillTags" label="Developer Competencies" />
9 <button type="submit">Save Settings</button>
10 </Form>
11</Formik>

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What does the useField hook return in Formik?
Question 2
How do you programmatically update a custom component's value in Formik without a standard onChange event?
Question 3
Why should helpers.setTouched(true) be called when a user interacts with a custom control?
Question 4
Can custom controls built with useField accept generic types (e.g. useField<string[]>(name))?
Question 5
What is the primary architectural advantage of building design system inputs with useField?
Next Lesson

High-Performance Form Optimization Comparison

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Multi-Step Wizards and Dynamic Schema Validation with YupHigh-Performance Form Optimization Comparison

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext