skip to Main Content

Hello I am programming chess board but components aren’t visible.
I cannot see those div’s "{square.id}" in this line


const horizontalLine = ["1", "2", "3", "4", "5", "6", "7", "8"];
const verticalLine = ["a", "b", "c", "d", "e", "f", "g", "h"];
const squares = [verticalLine.map((verticals) => (
  horizontalLine.map((horizontals) => (
    {
      id: `${verticals+horizontals}`,
      ver: `${verticals}`,
      hor: `${horizontals}`
    }
  ))
))];

function App() {

  return (
    <div className='App'>
      {squares.map((square) => (
        <div id={square.id} key={square.id}>{square.id}</div>
      ))}
    </div>
  );
}

export default App;

2

Answers


  1. React components not showing

    squares is an array of arrays of arrays and you are actually using only one loop. I would suggest to get rid of one wrapping array and add an additional inner loop.

    const horizontalLine = ["1", "2", "3", "4", "5", "6", "7", "8"];
    const verticalLine = ["a", "b", "c", "d", "e", "f", "g", "h"];
    const squares = verticalLine.map((verticals) => ( // remove wrapping array
      horizontalLine.map((horizontals) => (
        {
          id: `${verticals+horizontals}`,
          ver: `${verticals}`,
          hor: `${horizontals}`
        }
      ))
    ));
    
    function App() {
      return (
        <div className='App'>
          {squares.map((square) => (
            square.map((innerSquare) => ( // additional loop
               <div id={innerSquare.id} key={innerSquare.id}>{innerSquare.id}</div>
            ))
          ))}
        </div>
      );
    }
    

    https://codesandbox.io/s/practical-dawn-q5jjpm?file=/src/App.js

    Login or Signup to reply.
  2. Your squares object is an array with single element which is 8×8 2-dimensional matrix. When rendering the squares matrix, you are looping through only that single element. You need to access to first element squares array and then loop through both rows and then columns:

    {squares[0].map((row) => (
      row.map((square) => (
        <div id={square.id} key={square.id}>{square.id}</div>
      )
    )))}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search