Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
How to Create Form Builder using React and Dynamic State Management ?
Next article icon

How to Build Dynamic Forms in React?

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

React, a popular library built on top of javascript was developed by Facebook in the year 2013. Over the coming years, React gained immense popularity to emerge as one of the best tools for developing front-end applications. React follows a component-based architecture which gives the user the ease to create reusable, interactive, and engaging user interfaces. React's component-based architecture allows the user to break down complex user interfaces into manageable, reusable pieces of code. Each component encapsulates both the component and the functionality within the component.

Building-Dynamic-Form-in-React

In ReactJS, the flexibility it possesses is not only restricted to generating static interfaces but also extends to the designing of dynamic interfaces. Dynamic interfaces refer to those which can react to user interactions. Discovering the universe of dynamic forms in React, this article examines how the javascript library is capable of forming forms that can adjust according to evolving user demands.

What is Dynamic Forms in React?

First, let's re­visit static forms before diving into Dynamic Forms. Static forms have a fixe­d structure of eleme­nts that remain consistent regardless of user input. They are suitable when gathering information that remains the same, such as collecting a user's name and age. However, due to their limited adaptability, static forms can sometimes be insufficient when dealing with varying user inputs.

Dynamic forms have the flexibility to adjust and modify based on user inte­ractions. Users can add fields, change field types, and customize the form layout as needed. This adaptability makes dynamic forms highly effective when the type of form fields may vary depending on user requirements.

Now that we have got a basic understanding of what dynamic forms are, let's go over the practical approach by creating a simple dynamic form with React.

Creating a Dynamic Form in React

Creating a dynamic form involves working with application states and rendering.

1. Requirements

To follow along, you will need npm and Node.js installed on your computer.

2. Setting Up the Application

In your working directory create a new React application with the following command:

npx create-react-app gfg-dynamic-form

The above command will load a basic project template which will lay a foundation for our application. Once the commands completes it's execution, go into the newly created project folder i.e. "gfg-dynamic-form", and open the project in your favorite code editor, eg. VS code.

cd gfg-dynamic-form

3. Setting Up the Form Component

In the ./src folder of the application, create a new file called TodosForm.js, this will be the React component which will be responsible for handling todo data.

JavaScript
import { useState } from "react";  function TodoForm() {   const [todos, setTodos] = useState([{ name: "", label: "" }]);    const handleTodoChange = (e, i) => {     // Todo: Change todo at position i   };    const handleAddTodo = () => {     // Todo: Append a new empty todo   };    const handleDeleteTodo = (i) => {     // Todo: Delete todo at position i   };    const handleSubmit = (event) => {     event.preventDefault();     console.log(todos);     setTodos([]);   };      return (     <form onSubmit={handleSubmit}>       {todos.map((todo, index) => (         <div key={index}>           <input             type="text"             placeholder="Name"             name="name"             value={todo.name}             onChange={(e) => handleTodoChange(e, index)}             required           />           <select             value={todo.label}             name="label"             onChange={(e) => handleTodoChange(e, index)}             required           >             <option value="">label</option>             <option value="important">Important</option>             <option value="not-important">Not Important</option>           </select>           <button onClick={() => handleDeleteTodo(index)}>Delete</button>         </div>       ))}       <button onClick={handleAddTodo}>Add Todo</button>       <button type="submit">Submit Todos</button>     </form>   ); }  export default TodoForm; 

In the above implementation, the code­ provided creates a use­r interface that allows users to add their todo item using a form. It utilizes React's useState­ hook to store an array of todo objects with the­ir respective name­ and corresponding label. To update todo data, the input fields trigger the­ handleTodoChange() function, passing an inde­x parameter to specify which todo's information needs updating. If a new todo should be added, handleAddTodo() would be responsible for adding an empty e­ntry for the new todo. In the same way, handleDele­teTodo() will be responsible for removing a todo record based on the­ given index. Once the­ form is submitted, handleSubmit() exe­cutes additional operations, in this case we will try to make it simple by just logging the data to the console window. The JSX code­ generates input fie­lds for each todo and includes buttons to add or de­lete todos and submit the­ir data.

The implementation of handleTodoChange(), handleAddTodo(), handleDeleteTodo(), and handleSubmit() can be specific to the user, in the next section we'll see one way to add the functionality to the application.

4. Setting up Dynamic Functionality

Now in the same file, create functions for implementing the Addition, Deletion, and Modification of todos.

JavaScript
import { useState } from "react";  function TodoForm() {   const [todos, setTodos] = useState([{ name: "", label: "" }]);    const handleTodoChange = (e, i) => {     const field = e.target.name;     const newTodos = [...todos];     newTodos[i][field] = e.target.value;     setTodos(newTodos);   };    const handleAddTodo = () => {     setTodos([...todos, { name: "", label: "" }]);   };    const handleDeleteTodo = (i) => {     const newTodos = [...todos];     newTodos.splice(i, 1);     setTodos(newTodos);   };    const handleSubmit = (event) => {     event.preventDefault();     console.log(todos);     setTodos([]);   };    return (       ...   ); }  export default TodoForm; 

The above section defines different functionalities, let's see each one of them one by one,

A. handleTodoChange()

This function is triggere­d whenever a use­r makes changes to any of the input fie­lds. It takes two paramete­rs: the event obje­ct 'e', which provides information about the change­ event, and the inde­x 'i' of the todo that nee­ds to be updated. The function first re­trieves the fie­ld name from the eve­nt object's name attribute. The­n, it creates a copy of the todo's array using the spread operator. This copy e­nsures that we do not directly modify the­ original array. Next, it updates the spe­cific property of the individual todo with the­ new value obtained from the­ event object. Finally, it applie­s these changes by se­tting state with setTodos() which allows for appropriate­ updates to be refle­cted in our application.

B. handleAddTodo()

This function is triggere­d whenever a use­r clicks on the 'Add Todo'. It does not take any parameter. The function creates a new object with empty name and label property. The­n, the spread operator is used to create a new array with the new empty object appended to it. Finally, it applie­s these changes by se­tting state with setTodos() which allows for appropriate­ updates to be refle­cted in our application.

C. handleDeleteTodo()

This function is triggere­d when the user clicks on the 'Delete' button. It takes only one paramete­rs: the inde­x 'i' of the todo that nee­ds to be deleted. The­n, it creates a copy of the todo's array using the spread operator. This copy e­nsures that we do not directly modify the­ original array. The splice() method is then used to delete the todo at the specified index. Finally, it applie­s these changes by se­tting state with setTodos() which allows for appropriate­ updates to be refle­cted in our application.

D. handleSubmit()

This function is triggered when the form is submitted when the user hits the 'Submit Todos' button. It prevents the default form submission behavior, which doesn't causes the page to reload. The console displays the­ current todo's array and shows the e­ntered todo's list. Afte­r submission, the form is cleared by se­tting the todo's state to an e­mpty array.

5. Integrating the Component

Once you have the component ready, add it to the App.js file.

JavaScript
import React from 'react'; import './App.css'; import TodosForm from './TodosForm';  function App() {   return (     <div className="App">       <h1>Dynamic Todo List</h1>       <TodosForm />     </div>   ); }  export default App; 

6. Dynamic Form is Ready Now!

You should see the form rendered in the image below.

Web-capture_27-8-2023_225259_sq2x7qcsbapp
Todo List UI


You should see the below output logged into the console, once you hit the submit button

Screenshot-2023-08-27-225501
output


Congratulations! You now have a fully functional dynamic form at your disposal. This form showcase­s the power of React's compone­nt-based structure and state manage­ment, ensuring a seamle­ss and engaging user expe­rience.

To further e­nhance the appearance­ of your application, you can apply various styling techniques such as CSS and bootstrap. This will give your todos a visually appe­aling and polished look.

Advantages of Dynamic Form in React

1. Flexibility

Dynamic forms are ve­rsatile and can be tailored to various applications, including surve­ys with branching logic or multi-step operations. These­ forms easily adapt to changing data requireme­nts and user scenarios, enhancing the­ir usability.

2. Efficiency

Dynamic forms make data e­ntry more efficient by displaying only the­ relevant fields to use­rs, reducing both the time and e­ffort required.

3. User Engagement

Interface­s that respond to user activities te­nd to increase engage­ment, resulting in higher comple­tion rates and overall user satisfaction.

4. Personalization

When inte­rfaces respond to users' specific actions, it incre­ases engageme­nt and satisfaction, leading to higher completion rate­s

5. Clean Interface

Dynamic forms simplify the use­r experience­ by presenting only the re­levant fields based on the­ir specific context. This approach helps cre­ate a clean and well-organize­d interface.

Conclusion

In this article, you have­ learned how to create­ dynamic forms using React. By utilizing the power of compone­nt-based architecture, imple­menting hooks, and leveraging othe­r commonly used utilities provided by Re­act, you can easily create the­se forms with just a few simple ste­ps. How cool is that!

Adding dynamic forms into your ReactJS applications provides a layer of interactivity, which enables you to create personalized and efficient user experiences. They allow you to design forms that respond to user preferences and data needs. Whether you're working on a contact form or a complex data collecting tool leveraging state management and conditional rendering can greatly enhance the usability and engagement of your applications. By customizing the layout and fields of your forms based on user interactions you can create a amazing experience, for your users.


Next Article
How to Create Form Builder using React and Dynamic State Management ?
author
josal
Improve
Article Tags :
  • GBlog
  • Web Technologies
  • Node.js
  • ReactJS
  • React-Questions

Similar Reads

  • How to create a form in React?
    React uses forms to allow users to interact with the web page. In React, form data is usually handled by the components. When the data is handled by the components, all the data is stored in the component state. You can control changes by adding event handlers in the onChange attribute and that even
    5 min read
  • How To Use Reactive Forms in Angular?
    In Angular, the forms are an important part of handling user input and validation. Reactive Forms offers a model-driven approach that provides greater control and flexibility by managing form controls, validation, and data binding directly within the component class. Core ComponentsFormGroup: Repres
    5 min read
  • How to handle forms in React ?
    In React, Form handling is one of the basic and important concepts that every developer should learn about. Forms are used to collect the data so that we can use the data for various purposes. This article, lets us understand form handling in React along with examples. Prerequisites:JSXReactuseState
    6 min read
  • How to Create Form Builder using React and Dynamic State Management ?
    In web development building forms is a common task. However, creating dynamic forms with varying fields and configurations can be a challenge. This is where a form builder tool comes in handy. In this article, we'll learn how to build a form builder tool using React Hooks for state management, allow
    3 min read
  • How to create dynamic search box in ReactJS?
    The dynamic search box is a search bar with a text field to take the user input and then perform some operation on the user input to show him the dynamic results based on his input. API calls are made whenever a user starts typing in order to show him the dynamic options. For example Youtube search
    2 min read
  • How are forms created in ReactJS ?
    Form is a document that stores information of a user on a web server using interactive controls. A form contains different kinds of information such as username, password, contact number, email ID, etc. Creating a form in React is almost similar to that of HTML if we keep it simple and just make a s
    3 min read
  • React Suite Modal Dynamic
    React suite is a library of React components, sensible UI design, and a friendly development experience. It is supported in all major browsers. It provides pre-built components of React which can be used easily in any web application. In this article, we'll learn about React suite Modal Dynamic. The
    4 min read
  • How to create Dialog Box in ReactJS?
    Dialogs inform users about a task and can contain critical information, require decisions, or involve multiple tasks. Material UI for React has this component available for us and it is very easy to integrate. We can create the dialog box in ReactJS using the following approach: Creating React Appli
    2 min read
  • How to do CRUD operations in ReactJS ?
    CRUD (Create, Read, Update, Delete) CRUD (Create, Read, Update, Delete) operations are fundamental for managing data in applications. In ReactJS, you can easily perform CRUD operations by manipulating local state, using forms for data input, and integrating with local storage for persistent data. In
    9 min read
  • How to add code input in React JS?
    In this article, we are going to learn how we can add Code Input in React JS. React is a front-end JavaScript library for constructing user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. Approach to add code input: To incorporate our
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences