Search code examples
javascriptreactjscomponentsstatesetstate

How to update the state of a string using previous state


I am new to React and Javascript. I have a class component with a constuctor and function that look like this:

class MyComponent extends Component {
constructor(props) {
    super(props)
    this.state = {
       HTMLTable : ""  
    }
createGrid ()
{
    for(let row = 0; row <= 20;row++)
    {
        let currentHTMLRow = `<tr id = "Row ${row}">`;
        for(let col = 0; col < 50; col++)
        {
            let newNodeId = `${row}_${col}`;
            let NodeClass = "unvisited";
            currentHTMLRow = currentHTMLRow +`<td id = "${newNodeId}" class = "${NodeClass}"></td>`
        }
        this.state.HTMLTable += `${currentHTMLRow}</tr>`;
    }
    let chart = document.getElementById("grid");
    chart.innerHTML = this.state.HTMLTable;
}
}

This produces the desired effect but I have been warned against changing the value of the state like this

this.state.HTMLTable += `${currentHTMLRow}</tr>`;

*How do I change the state of the HTMLTable String using setState() everytime the loop iterates such that: this.state.HTMLTable += ${currentHTMLRow}</tr>; *


Solution

  • the way you change the state using a previous state is this:

    this.setState(prevState => {
       return {HTMLTable: prevState.HTMLTable + whatever you want};
    });