Knows Not Much
Knows Not Much

Reputation: 31526

Why are the props undefined for my React Component

I wrote this react component

class Row extends React.Component {
   constructor(props) {
      super(props);
      this.style = {
         display: "flex"
      }
   }
   render(){
      var rowcells = [];
      for(let i = 0; i < 7; i ++) {
         console.log("foo " + this.props.cells)                           
         rowcells.push(<Cell key={i} col ={i} row={this.props.row} cell={this.props.cells[i]} handleClick={this.props.handleClick}/>)
      }
      return (
         <div style = {this.style}>
            {rowcells}
         </div>
      )
   }
}

this component is called only once in my application like

for(let i = 6; i > 0; i--) {
  rows.push(<Row key={i} row={i} cells={this.props.cells[i]} handleClick={this.props.handleClick}/>)
}

So you can see that the props.cells is defined. but when my code runs it fails by at the line this.props.cells[I] by saying its undefined

https://codepen.io/knows_not_much/pen/dddNRZ?editors=1111

This is a example from the react tutorial here

https://courses.edx.org/courses/course-v1:Microsoft+DEV281x+1T2018/courseware/404dd3a7096e46c5b4672e26e5a5b404/70c54b9d11ef4439a2996f9826ba6375/?child=last

The only difference between the sample and my code is that I am closing the component style rather than function style for react components.

Upvotes: 0

Views: 394

Answers (2)

Amin Jafari
Amin Jafari

Reputation: 7207

In the code below you're not iterating over the first item of the array which is index 0, and also as @Govind suggested the i=6 must be i=5, so this:

for(let i = 6; i > 0; i--) {
  rows.push(<Row key={i} row={i} cells={this.props.cells[i]} handleClick={this.props.handleClick}/>)
}

must be this:

for(let i = 5; i >= 0; i--) { //notice the greater or equal sign (>=)
  rows.push(<Row key={i} row={i} cells={this.props.cells[i]} handleClick={this.props.handleClick}/>)
}

See it in action

Upvotes: 1

Govind Rai
Govind Rai

Reputation: 15780

Your for loop logic when creating Row components (inside your Board Component) has an error: You're accessing a item of the cells array which does not exist. It should be let i = 5 since the array has six elements and is 0 indexed not let i = 6.

Couple of console.log statements helped me to the issue.

Upvotes: 1

Related Questions