Ian Springer Ian Springer -4 years ago 129
React JSX Question

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{
this.state = {
myArray: Array(64).fill(null),
checked: false
this.state.myArray.map(function(obj, key){
return <Square key={key} checked={this.state.checked} />
}, this)

<div className="wrapper">

export default Board;

Answer Source

Your renderSquares is missing a return.

return this.state.myArray.map etc.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download