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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With