Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

duplicate component onclick React

I"m new to react, I'm creating a registration from. I want the user to be able to click a button to add an additional person to the registration. I have a "person" component which holds the form fields, onclick I want to duplicate that component.

import React, { useRef } from 'react'
import Person from './Person'

function BookingForm() {
    const registrationForm = useRef()
    console.log(registrationForm.current)
    let handleAddPerson = (e) => {
        e.preventDefault()
        registrationForm.appendChild(<Person/>)
    }
    
    return (
        <>
        <form ref={registrationForm} id='registrationForm'>
            <Person/>
            <button onClick={handleAddPerson}  className="btn btn-main mt-2"><i className="fas fa-plus"></i> ADD PERSON</button>
        </form>
        </>
    )
}

export default BookingForm

like image 538
Julius Avatar asked Dec 04 '25 06:12

Julius


1 Answers

I would like to recommend you implement it using state instead of ref. Like below:

import React, { useState } from 'react'
import Person from './Person'

function BookingForm() {
    const [persons,setPerson] = useState([<Person key={0} />]);

    let handleAddPerson = (e) => {
        e.preventDefault()
        setPerson([...persons,<Person key={persons.length} />]);
    }
    
    return (
        <>
        <form id='registrationForm'>
            {persons}
            <button onClick={handleAddPerson}  className="btn btn-main mt-2"><i className="fas fa-plus"></i> ADD PERSON</button>
        </form>
        </>
    )
}

export default BookingForm;

Hope this will help you. Using state is better in this case.

like image 96
Vijay Kumar Avatar answered Dec 06 '25 18:12

Vijay Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!