0

I am initialising myComponents array with useState hook

const [myComponents, setMyComponents] = useState([])

Then I am adding components to the array upon clicking of a button

setMyComponents([...myComponents, <MyComponent />])

MyComponent:

function MyComponent(props) {
  return (
    <div class="flex">
      <button>DELETE</button>
      <p>Some text...</p>
    </div>
  )
}

When any of the DELETE buttons pressed, relevant MyComponent from the myComponents array should be removed. I cannot figure out how to get a reference to the component I have to delete. I cannot use the array index since when the first component is removed from the array, previous indices are no longer valid.

Please let me know how can I delete a particular MyComponent from the array so that it won't affect subsequent deletions.

Lakmal Premaratne
  • 1,159
  • 7
  • 18
  • 34

1 Answers1

1

that is not how you would go about rendering data in react , generally you would map over a list of data and render components like this below , so when you need to remove an item you just remove the item from the data list and the Listcomponent will re-render with the new data :

function MyComponent(props) {
const {index,text,deleteItem} = props
  return (
    <div class="flex">
      <button onClick={e=>deleteItem(index)}>DELETE</button>
      <p>{text}</p>
    </div>
  )
}

function MyComponentList(props) {
  const [mydata, setmydata] = useState(["text1","text2","text3"])

 const deleteItem=(index)=>{
      const filterdData= [...mydata].filter((data,i)=> i != index)
      setmydata(filterdData)
 }
  return (
     {
        mydata.map((text,index)=><MyComponent key={index} text={text} index={index} deleteItem= {deleteItem} />
     }
  )
}

سعيد
  • 1,547
  • 1
  • 14
  • 32