Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

259
Visualizações
Using a 2D map in React to print a chessboard

I am pretty new to react but instead of using the common js for loop I am trying to figure out how to use the .map() to achieve the same result.

 import React from 'react'
 import './styles/Board.css'
 import Tile from './Tile'
    
    const Board = () => {
        let board = []
        printBoard(board)
        return (
            <div className="board">
                { board }
            </div>
        )
    }
    
    const printBoard = (board) => {
        
        const boardY = [1, 2, 3, 4, 5, 6, 7, 8]
        const boardX = ['a','b','c','d','e','f','g','h']
        
        for(let x = 0; x < boardX.length; x++) {
            for(let y = boardY.length - 1; y >= 0; --y) {
                //saves the position in each square ex: b1
                const pos = boardX[x] + "" + boardY[y]
                //paints the squares and the positions
                board.push(<Tile key={pos}  color={ (x + y) % 2 === 0 ? "dark" : "light" } pos={pos} />)
            }
        }
    }
    export default Board

Current render

enter image description here

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You need to switch the loops (outer and inner) when doing the same with map function. And the y had to be replaced with (boardY.length - (yIndex + 1)) to get the decrementing index.

Try below

const Board = () => {
    return <div className="board">{printBoard()}</div>;
};

const printBoard = () => {
    const boardY = [1, 2, 3, 4, 5, 6, 7, 8];
    const boardX = ["a", "b", "c", "d", "e", "f", "g", "h"];
    const boardYRevered = boardY.reverse();

    return boardYRevered.flatMap((y, yIndex) => {
        return boardX.map((x, xIndex) => {
            const pos = `${x}${y}`;
            return (
                <Tile
                    key={pos}
                    color={
                        (xIndex + (boardY.length - (yIndex + 1))) % 2 === 0
                            ? "dark"
                            : "light"
                    }
                    pos={pos}
                />
            );
        });
    });
};

NOTE: If you want a 2D array of the chessboard, change flatMap to map.

about 4 years ago · Juan Pablo Isaza Relatório

0

import React from "react";

const Board = () => {
  const boardY = [1, 2, 3, 4, 5, 6, 7, 8];
  const boardX = ["a", "b", "c", "d", "e", "f", "g", "h"];
  const reverseY = boardY.reverse();

  return (
    <div className="board">
      {boardX.map((xValues,indexX) =>
        reverseY.map((yValues, indexY) => {
          const pos = xValues + "" + yValues;
          const colorIndex = indexX + indexY;
          <Tile key={pos}  color={ colorIndex % 2 === 0 ? "dark" : "light" } pos={pos} />
        })
      )}
    </div>
  );
};
export default Board;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda