Home > Back-end >  Index values from map method won't save to id of div
Index values from map method won't save to id of div

Time:07-19

I'm building a chess board app and currently am trying to assign each square a unique id that will corelate to it's position in the 2d array. For example, the first rook in boardInit should have an id of [0, 0].

let boardInit = [
  ['rook', 'knight', 'bishop', 'queen', 'king', 'bishop', 'knight', 'rook'],
  ['pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn'],
  [null, null, null, null, null, null, null, null],
  [null, null, null, null, null, null, null, null],
  [null, null, null, null, null, null, null, null],
  [null, null, null, null, null, null, null, null],
  ['pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn', 'pawn'],
  ['rook', 'knight', 'bishop', 'queen', 'king', 'bishop', 'knight', 'rook'],
];

const Board = () => {
  return (
    <div>
      <div className='board-cont'>
        {boardInit.map((row, x) => {
          return row.map((col, y) => {
            return (
              <div
                id={y   x}
                className='board-sqr'
                onClick={() => console.log(this.id)}
              >
                {col}
              </div>
            );
          });
        })}
      </div>
      <MoveMessage clicks={clickState} />
    </div>
  );
};

When I map through the array to create the board, both the x and y values are correct for the position. I can see them display accurately when I console log them out. However when I try to assign the id to these values and console log it, I get an error that id is undefined. How do I got about assigning the x and y values to use as an id for each square?

CodePudding user response:

I think the issue you're running into is that x y is performing a mathematical addition of x and y. To get your desired string id of [x,y], you can do the following

return (
    <div>
      <div className="board-cont">
        {boardInit.map((row, x) => {
          return row.map((col, y) => {
            const id = `[${x},${y}]`

            return (
              <div
                id={id}
                className="board-sqr"
                onClick={() => console.log(id)}
              >
                {col}
              </div>
            );
          });
        })}
      </div>
    </div>
  );
  • Related