Home > front end >  How to create loop inside React return?
How to create loop inside React return?

Time:09-22

I just learn React so i have a question. I develop the Tic-toe game which is stayed in the official documentation. There are extra-tasks bellow the "Tutorial". One of them is

"Rewrite Board to use two loops to make the squares instead of hardcoding them."

We have this code for generation playing field:

 return (
  
  <div>
    <div className="board-row">
      {this.renderSquare(0)}
      {this.renderSquare(1)}
      {this.renderSquare(2)}
    </div>
    <div className="board-row">
      {this.renderSquare(3)}
      {this.renderSquare(4)}
      {this.renderSquare(5)}
    </div>
    <div className="board-row">
      {this.renderSquare(6)}
      {this.renderSquare(7)}
      {this.renderSquare(8)}
    </div>
  </div>
);

But we should remake this using any loop. I started to search information about this but found solution only with using map. So now i have code like this:

const mas = Array(3).fill(null)

let i = -1;
return(
    <div>
      {mas.map(() =>{
        return(
        <div className = "board-row">
            {mas.map(() => {
                i = 1;
                return (<span key={i}>{this.renderSquare(i)}</span>);
            })}
        </div>)
      })}
    </div>
)

Probably there is another solution of this task... Using for example for loop or something like this...

CodePudding user response:

This is absolutely fine, but another option would be exporting the rows to their own component, this way you would be able to return the following:

{[1,2,3].map((key) => <Row key={key} />)}

And the row component could return the following

{[1,2,3].map((key) => <span key={key}>renderSquare(key)</span>)}

CodePudding user response:

    const renderItems = [
    {
        id: 0
    },
    {
        id: 1
    },
    {
        id: 2
    },
    {
        id: 3
    },
    {
        id: 4
    },
    {
        id: 5
    },
    {
        id: 6
    },
    {
        id: 7
    },
    {
        id: 8
    },
    {
        id: 9
    }
];

const Board = ({ itemNo }) => {
    return <p>{itemNo}</p>;
};

const BoardGame = () => {
    return (
        <div className='grid cols-3'>
            {renderItems.map(item => {
                return <Board key={item?.id} itemNo={item?.id} />;
            })}
        </div>
    );
};
  • Related