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" ponent which holds the form fields, onclick I want to duplicate that ponent.
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"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" ponent which holds the form fields, onclick I want to duplicate that ponent.
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
Share
Improve this question
asked Jan 22, 2022 at 3:20
JuliusJulius
731 silver badge6 bronze badges
1
-
Can you share the
person
ponent code ! – Mayur Vaghasiya Commented Jan 22, 2022 at 4:23
1 Answer
Reset to default 10I would like to remend 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.