Ian Springer
Ian Springer

Reputation: 233

Using loop outside of render function in React.js

I am building a checkers game using React.js, and I would like to create a loop that renders my "Square" component 64 times in order to create my "Board" component. I am able to render the Square components correctly when running the .map function inside of the render function. However, I don't like having the .map function taking place inside the render function, and would like to call a separate function that does the same thing inside the render function. When I move the .map function into the renderSquares function, the squares do not get rendered. Can someone explain what I'm missing here? Thanks.

import React, { Component } from "react";
import Square from "./Square";

class Board extends Component{
  constructor(){
    super()
    this.state = {
     myArray: Array(64).fill(null),
     checked: false
    }
    console.log(this.state.checked)
  }
  renderSquares(){
    this.state.myArray.map(function(obj, key){
      return <Square key={key} checked={this.state.checked} />
    }, this)
  }

  render(){
    return(
        <div className="wrapper">
          {this.renderSquares()}
        </div>
    )
  }
}

export default Board;

Upvotes: 0

Views: 1047

Answers (2)

nbkhope
nbkhope

Reputation: 7474

When you call this.renderSquares() inside the render function, the keyword this will not refer to the Board component inside the renderSquares() function. One way to fix that is to use bind:

{this.renderSquares.bind(this)}

I much prefer another way -- using the arrow function:

Instead of using renderSquares(), define it using:

renderSquares = () => { ... }

That way, the keyword this will be referring correctly to the Board component. Note that this approach might not work if you don't have the right babel presets installed (I always make sure to use the following babel presets: react, es2015, and stage-1)

Upvotes: 0

paqash
paqash

Reputation: 2314

Your renderSquares is missing a return.

return this.state.myArray.map etc.

Upvotes: 1

Related Questions