Home > Net >  ReactJS: Removing dynamically added component
ReactJS: Removing dynamically added component

Time:10-06

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

  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?

CodePudding user response:

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

setExamSections( prev => {
    prev.splice(index, 1)
    return [...prev]
})
  • Related