Search code examples
reactjsdomrenderingstatevirtual-dom

React - State data now showing in render


It appears to be updating the State Array based on the console log. Im probably missing something on how the render is working with the handler or the lifecycle itself (sorry still learning React). Should I be sending this to another component perhaps and then rendering that custom component on my page?? Here is the code simplified.

  handleRowSelect = (row, isSelected, e) => {
console.log("MYROW::", row);
console.log("MYSTATEROW1::", this.state.selected)
this.setState({ selected: this.state.selected.concat([row]) }, () => {
  console.log("MYSTATEROW2::", this.state.selected[0].ridername);
});
}


 render() {
   return (
     <h4>{this.state.selected[0].ridername}></h4>
    )
  }

When I was just adding a single element (not an array) I had no issues updating the state of my element, going from nothing to something basically. Now that im concating into my Array, Im guessing my lifecycle will not let me address the [0] index in the array when the page first loads?? Im sure im missing some order operations in this DOM (virtual DOM) lifecycle stuff. It's all pretty new to me. How do you deal with rendering State Array objects as they are added (starting with nothing obviously).


Solution

  • So looks like I needed to get friendly with the map function. I can return stuff now using this. Makes sense.

     <div>{this.state.selected.map((selected, index) => (
                <p key={index}>{selected.ridername}</p>
              ))}</div>
    

    Credit to this reference which keyed me into what I was doing.

    http://www.hackingwithreact.com/read/1/13/rendering-an-array-of-data-with-map-and-jsx