Galaxy Wanderer Galaxy Wanderer - 3 months ago 13
React JSX Question

JavaScript Creating array in object and push data to the array

I'm new to programming. I'm trying React and have function addComment which is executed when a user adds a comment to news.I need to create in this moment a property comments (array) and assign or push to this array inputCommentValue value. But right now I only rewrite 0 element of the array and can't add a new element.
Can you please tell me where to 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});
}

Answer

assuming that data exist in component's state , then handler will look something like that

addComment(index, inputCommentValue){
    // copy array , for not mutate state
    let ARTICLES = [...this.state.ARTICLES];
    // check if comments not exist
    if(!ARTICLES[index].comments) ARTICLES[index].comments=[];
    // add new comment to array
    ARTICLES[index].comments.push(inputCommentValue);
    // update component with new articles
    this.setState({ARTICLES:ARTICLES});
}
Comments