Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ReactJS: Removing dynamically added component

I’m trying to implement a form, where we have to add new row of component on a button click. Adding new component is working fine. Used below code to do that

    const onClickAddExamSection = () => {
    const uuid = getUniqueId();
    const data = [...examSections];
    data.push({
      index: uuid, data: <ScheduleExamSection key={uuid} className='row mt-4'
        index={uuid} onClickRemoveSection={onClickRemoveSection} />
    });
    setExamSections(data);
  };

Result will be like below image
enter image description here

When remove button is clicked, below function is called

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  const onClickRemoveSection = (index) => {
    const data = [...examSections];
    const filtered = data.filter(x => x.index !== index);
    setExamSections(filtered);
  };

Issue I’m facing is, when I click on the remove button of one row, all the rows below that is getting removed. While debugging I found that, when it reaches onClickRemoveSection examSections already having data removed. Nowhere else we are modifying examSections.

Remove button is in ScheduleExamSection component. That part of code is like below

{index !== '0' ?
                    <img src={del} className="App-logo" style={{ marginLeft: '20px', paddingTop: 45 }} alt="logo" 
                    onClick={() => deleteEntry(index)} /> : <></>}


const deleteEntry = (sn) => {
    console.log('clicked ' + sn);
    onClickRemoveSection(sn);
};

How to tackle this issue?

>Solution :

Proper way to do this in react is the following try it out:

setExamSections( prev => {
    prev.splice(index, 1)
    return [...prev]
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading