Categories

Monday, November 18, 2024
#919814419350 therichposts@gmail.com
Bootstrap 5Reactjs

Reactjs Append And Remove Form Fields Using Hooks

Reactjs Append And Remove Form Fields Using Hooks

react js append and remove form fields, React Add/Remove Input Fields Dynamically on button click.
Hello friends, welcome back to my blog. Today in this blog post, I am going to show you, Reactjs Append And Remove Form Fields Using Hooks.


Working Demo

Reactjs Append And Remove Form Fields Using Hooks
Reactjs Append And Remove Form Fields Using Hooks

For reactjs new comers, please check the below link:

Reactjs Basic Tutorials

Bootstrap 5 Tutorials


Friends now I proceed onwards and here is the working code snippet and please use this carefully to avoid the mistakes:

1. Firstly, we need fresh reactjs setup and for that, we need to run below commands into out terminal and also we should have latest node version installed on our system and bootstrap as well:

npx create-react-app reactdemo

cd reactdemo

npm install bootstrap

npm i @popperjs/core

npm start

2. Finally for the main output, we need to add below code into our reactdemo/src/App.js file or if you have fresh setup then you can replace reactdemo/src/App.js file code with below code:

import React, { useState } from 'react'
//useState is a Hook that lets you add React state to function components
import 'bootstrap/dist/css/bootstrap.min.css';

const App = () => {
   // Declare a new state variable, which we'll call "form fields"
    const [formValues, setFormValues] = useState([{ name: "", email : ""}])

    let handleChange = (i, e) => {
        let newFormValues = [...formValues];
        newFormValues[i][e.target.name] = e.target.value;
        setFormValues(newFormValues);
      }
    
    let addFormFields = () => {
        setFormValues([...formValues, { name: "", email: "" }])
      }
    
    let removeFormFields = (i) => {
        let newFormValues = [...formValues];
        newFormValues.splice(i, 1);
        setFormValues(newFormValues)
    }
    
    let handleSubmit = (event) => {
        event.preventDefault();
        alert(JSON.stringify(formValues));
    }

    return (
      <div className='container py-5'>
        <form  onSubmit={handleSubmit}>
          {formValues.map((element, index) => (
            <div className="mb-3 row g-3" key={index}>
              <div className="col-sm-6">
              <label>Name</label>
              <input type="text" name="name" class="form-control" value={element.name || ""} onChange={e => handleChange(index, e)} />
              </div>
              <div className="col-sm-6">
              <label>Email</label>
              <input type="text" name="email" class="form-control" value={element.email || ""} onChange={e => handleChange(index, e)} />
              </div>
              {
                index ? 
                <div className="col-sm text-end">
                  <button type="button"  className="button remove btn btn-danger" onClick={() => removeFormFields(index)}>Remove</button> 
                  </div>
                : null
              }
              </div>
            
          ))}
          <div className="button-section">
              <button className="button add btn btn-warning me-3" type="button" onClick={() => addFormFields()}>Add</button>
              <button className="button submit btn btn-primary" type="submit">Submit</button>
          </div>
      </form>
      </div>
    )
}

export default App

Now we are done friends. If you have any kind of query or suggestion or any requirement then feel free to comment below.

Note: Friends, I just tell the basic setup and things, you can change the code according to your requirements.

I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad.

Jassa

Thanks

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.