Building a Dynamic Form Component

 📝 Building a Dynamic Form Component

A dynamic form component is a form that can change its structure or fields based on data or user input. Instead of hardcoding every form field, you generate the form UI dynamically, which is useful when:


Form fields depend on external data or configuration.


The form needs to adapt to different user roles or contexts.


You want to reuse the same component for multiple forms.


Key Concepts

Form schema or configuration: Define the form fields, types, labels, validations, etc., in a JSON object or JavaScript structure.


Rendering form fields: Iterate over the schema and render appropriate input components.


State management: Keep track of the form values dynamically.


Validation: Validate each field based on the schema.


Example: React Dynamic Form Component

jsx

Copy

Edit

import React, { useState } from 'react';


const formSchema = [

  { name: 'firstName', label: 'First Name', type: 'text', required: true },

  { name: 'email', label: 'Email', type: 'email', required: true },

  { name: 'age', label: 'Age', type: 'number', required: false },

];


function DynamicForm({ schema }) {

  const [formData, setFormData] = useState({});


  const handleChange = (e) => {

    setFormData(prev => ({ ...prev, [e.target.name]: e.target.value }));

  };


  const handleSubmit = (e) => {

    e.preventDefault();

    // Simple validation

    for (const field of schema) {

      if (field.required && !formData[field.name]) {

        alert(`${field.label} is required`);

        return;

      }

    }

    alert('Form submitted: ' + JSON.stringify(formData));

  };


  return (

    <form onSubmit={handleSubmit}>

      {schema.map(field => (

        <div key={field.name} style={{ marginBottom: '1em' }}>

          <label>{field.label}: </label>

          <input

            type={field.type}

            name={field.name}

            value={formData[field.name] || ''}

            onChange={handleChange}

            required={field.required}

          />

        </div>

      ))}

      <button type="submit">Submit</button>

    </form>

  );

}


// Usage

export default function App() {

  return <DynamicForm schema={formSchema} />;

}

How It Works

The formSchema defines what fields to render.


The component loops over this schema and renders input fields.


State (formData) tracks values for each field by name.


On submit, it checks required fields and alerts the form data.


Advantages of Dynamic Forms

Easy to update or extend form structure without changing code.


Can load schema from server to create customizable forms.


Reusable for different forms by passing different schemas.

Learn React JS Course in Hyderabad

Read More

Validating Forms in React

Controlled vs Uncontrolled Components

Handling Form Inputs in React

Visit Our Quality Thought Training in Hyderabad

Get Directions 

Comments

Popular posts from this blog

Understanding Snowflake Editions: Standard, Enterprise, Business Critical

Why Data Science Course?

How To Do Medical Coding Course?