JavaScript Creating array in object and push data to the array -
i'm new programming. i'm trying react , have function addcomment executed when user adds comment news.i need create in moment property comments (array) , assign or push array inputcommentvalue value. right rewrite 0 element of array , can't add new element. can please tell me put push method? thank you!
var articles = [{ title: "sit amet erat", text: "nam dui proin leo odio porttitor id consequat in consequat ut nulla sed accumsan" }, { title: "pulvinar sed", text: "velit id pretium iaculis diam erat fermentum justo nec condimentum" }] addcomment(index, inputcommentvalue){ articles = [...articles], articles[index].comments=[inputcommentvalue]; this.setstate({articles:articles}); }
assuming data exist in component's state , handler that
addcomment(index, inputcommentvalue){ // copy array , not mutate state let articles = [...this.state.articles]; // check if comments not exist if(!articles[index].comments) articles[index].comments=[]; // add new comment array articles[index].comments.push(inputcommentvalue); // update component new articles this.setstate({articles:articles}); }
Comments
Post a Comment