Dynamic Form Handling

In this approach, the form is dynamic where you can add form fields as well and type into it. It is helpful in case you want to submit an array of inputs.

Example: The example demonstrates a functional component defined called `Dynamic Form`, that defines the logic of displaying an array of input fields.

Javascript




// App.js
 
import React, { useState } from 'react';
 
const App = () => {
    const [fields, setFields] = useState([{ value: '' }]);
 
    const handleChange = (index, event) => {
        const values = [...fields];
        values[index].value = event.target.value;
        setFields(values);
    };
 
    const handleAddField = () => {
        setFields([...fields, { value: '' }]);
    };
 
    const handleRemoveField = (index) => {
        const values = [...fields];
        values.splice(index, 1);
        setFields(values);
    };
 
    const handleSubmit = (event) => {
        event.preventDefault();
        console.log('Form submitted with fields:', fields.map(field => field.value));
    };
 
    return (
        <div style={{ marginTop: '60px', fontFamily: 'Arial, sans-serif', maxWidth: '400px', margin: 'auto' }}>
            <h2 style={{ fontSize: '24px', marginBottom: '16px' }}>Dynamic Form Fields</h2>
            <form onSubmit={handleSubmit} style={{ marginBottom: '16px' }}>
                {fields.map((field, index) => (
                    <div key={index} style={{ marginBottom: '8px' }}>
                        <input
                            type="text"
                            value={field.value}
                            onChange={(event) => handleChange(index, event)}
                            style={{ padding: '8px', marginRight: '8px', border: '1px solid #ccc',
                            borderRadius: '4px', width: '200px' }}
                        />
                        <button type="button" onClick={() => handleRemoveField(index)} style={{ padding: '8px',
                        background: 'red', color: '#fff', border: 'none', borderRadius: '4px', cursor: 'pointer' }}>
                        Remove</button>
                    </div>
                ))}
                <button type="button" onClick={handleAddField} style={{ marginTop: '10px', padding: '8px',
                background: 'green', color: '#fff', border: 'none', borderRadius: '4px', cursor: 'pointer',
                marginRight: '8px' }}>Add Field</button>
                <button type="submit" style={{ padding: '8px', background: 'blue', color: '#fff', border: 'none',
                borderRadius: '4px', cursor: 'pointer' }}>Submit</button>
            </form>
        </div>
    );
};
 
export default App;


Output:

Start the server by running the following command

npm start

output example 2



Form Handling with React Hooks

Forms are an important part of web development. Form handling is a crucial user interaction for websites. React hooks provide a concise and very efficient way to handle the state of the form as the user interacts with the form fields. There are mainly two react hooks for this purpose.

  1. useState:- useState hook is used to manage the current state of any input field in the context of form handling. useState is a very nice way to hold the data over the website till the time you want.
  2. useEffect: useEffect is used to perform side effects on the website. use effect can be used to trigger actions after successful form submission as shown in example one. useEffect can also be used in case the form requires additional data to be fetched from the server, such as options of the `select` form field.

In this article, we will learn how to efficiently manage forms using react hooks.

Similar Reads

Prerequisites:

Basic understanding of React concepts Familiarity with JSX syntax Node.js and npm installed...

Steps to Create a React App

Step 1: Create a new react application using the commands provided below....

Approach 1: Basic form Handling

Basic form handling defines a state where the form data is held as input by the user....

Approach 2: Dynamic Form Handling

...

Contact Us