Home > database >  Whats the best way to make use of a counter variable in this nested 'map' loop so that eac
Whats the best way to make use of a counter variable in this nested 'map' loop so that eac

Time:02-02

    return (
    <div>
        <div className="board">
        {
            [1,2,3].map( (row) => {
                    return <div key={row} className="board-row">
                {
                    [1,2,3].map( (col) => {
                        return <Square key={col}></Square>
                    })
                }
                </div>

            })
        }
        </div>
    </div>
  );

How might i make it so the Squares generated by this nested for loop (using array map functions) could use a counter so that the square's value would be 0 to 8 or 1 to 9.

I am struggling to create a variable outside of these javascript arrow functions...

(I have a Java background and am struggling i little wrapping my head around javascript/react :) )

Many thanks for any help/direction.

John

EDIT:

Below is solution that worked for me in the end!

{
            [1,2,3].map( (row) => {
                    return <div key={row} className="board-row">
                {
                    [1,2,3].map( (col) => {
                        return this.renderSquare(  count);
                    })
                }
                </div>

            })
        }
        </div>

Here is renderSquare function also:

renderSquare(i) { return ( <Square value={this.props.squares[i]} onClick={() => this.props.onClick(i)} key = {i} /> ); }

I think a lot of the confusion is because of JSX and learning how and when you can type HTML and/or JavaScript where.

FINAL EDIT: please note, i changed from count to count to avoid the initial increment occurring too early. Doing this breaks the calculateWinner logic, just if anyone else is doing the tic tac toe tutorial! :)

CodePudding user response:

If you just want to count and output the number of times the second loop is called then the following is a solution to it:

import React from 'react';

export default function Test2() {
  let count = 0;

  return (
    <div>
      <h1>Test 1 Component</h1>
      {[1, 2, 3].map((row) => {
        return (
          <div key={row}>
            {[1, 2, 3].map((col) => {
              return <div key={col}>{  count}</div>;
            })}
          </div>
        );
      })}
    </div>
  );
}
  •  Tags:  
  • Related