Home > Software design >  Undefined variable using .map() react
Undefined variable using .map() react

Time:10-01

I'm revisiting an old project for coursework at school but I keep getting an error for an undefined grid variable for generating my grid.

I want to loop for the amount of rows and columns which I want to store the properties for in an array called grid. Then I want to display nodes for the rows and columns in the array with .map().

I'm pretty new to react though and can't seem to find why I can't access the grid array within render().

class PathfinderGrid extends Component {
  constructor(props) {
    super(props)
    this.state = {
      grid: [],
    };
  }
  

  componentDidMount() {
    const grid = createGrid();
    this.setState({ grid });
    //console.log(this.state.grid)
  }

  render() {
    return (
      <div>
        {grid.map((grid) => {
          <div>{ grid }</div>
        })}
      </div >
    );
  }
}



const createGrid = () => {
  let grid = [];
  for (let row = 0; row < 15; row  ) {
    let currentRow = [];
    for (let col = 0; col < 50; col  ) {
      currentRow.push();
    }
    grid.push(currentRow);
    //console.log(grid);

  }
  return grid;
};

export default PathfinderGrid;

CodePudding user response:

Since you are using class component, I believe you need to write

 {this.state.grid.map((grid) => {
   return <div>{ grid }</div>
 })}
  • Related