Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

191
Views
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

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!