Skip to content Skip to sidebar Skip to footer

Can't Remove Specific Elements From Array By Index Number From Dynamic Div Element In React?

I can't remove specific elements of array by index number from any dynamic div When i want to remove any specific div then not only this div remove from array, also remove next di

Solution 1:

Your RemArr function has a closure over Children, meaning that clicking on the remove button will call a potentially old declaration of remArr, where inside that remArr, the Children array will refer back to the Children array state from when you originally added the click event handler, rather than the current state of Children.

To overcome this, you can componentize Product rather than making it a function, and drive the Children based of some state in Choice, which you can use to generate your Product elements:

const {useState} = React;

functionProduct({docs, onClick}){
  return<React.Fragment><buttononClick={onClick}>
      List {docs.i}
    </button><p></p><input/><p></p></React.Fragment>;
}

functionCheck() {
  const [products, setProducts] = useState([]);
  functionremArr(index){
    const temp = [...products];
    temp.splice(index, 1);
    setProducts(temp);
  }
  
  functionaddProduct() {
    const prevNum = products[products.length-1];
    setProducts([...products, {
      fix: false, 
      i: prevNum === undefined ? 0 : prevNum.i + 1
    }]);
  }

  return (<React.Fragment><div>Check</div>
    {products.map(
      (doc, i) => <Productkey={doc.i}docs={doc}onClick={() => remArr(i)}/>
    )}
    <buttononClick={addProduct}
    >Add List</button></React.Fragment>);
}

ReactDOM.render(<Check />, document.body);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>

The above .map() method that creates new <Product /> components "updates"/re-sets the onClick function of all the product components to point to the "latest" declared remArr function, which has access to the correct/up to date products array. This is unlike your example, where the old JSX objects inside of the Children array still have onClick attributes that refer to the old declarations of the remArr function (which have access to the old Children array state)

Post a Comment for "Can't Remove Specific Elements From Array By Index Number From Dynamic Div Element In React?"