skip to Main Content

Hello I was doing React chess app but the components are not showing.
I checked the Image paths and I think they are correct. I also checked if ".map()" function has no problem with the link. Also black squares are missing before I added images they were visible. So I don’t know what the problem can be.

here is the code:

import React from 'react';
import './App.css';

const horizontalLine = ["8", "7", "6", "5", "4", "3", "2", "1"];
const verticalLine = ["a", "b", "c", "d", "e", "f", "g", "h"];

const pieces = {
  "a1": "white-rook.png",
  "b1": "white-knight.png",
  "c1": "white-bishop.png",
  "d1": "white-queen.png",
  "e1": "white-king.png",
  "f1": "white-bishop.png",
  "g1": "white-knight.png",
  "h1": "white-rook.png",
  "a2": "white-pawn.png",
  "b2": "white-pawn.png",
  "c2": "white-pawn.png",
  "d2": "white-pawn.png",
  "e2": "white-pawn.png",
  "f2": "white-pawn.png",
  "g2": "white-pawn.png",
  "h2": "white-pawn.png",
  "a8": "black-rook.png",
  "b8": "black-knight.png",
  "c8": "black-bishop.png",
  "d8": "black-queen.png",
  "e8": "black-king.png",
  "f8": "black-bishop.png",
  "g8": "black-knight.png",
  "h8": "black-rook.png",
  "a7": "black-pawn.png",
  "b7": "black-pawn.png",
  "c7": "black-pawn.png",
  "d7": "black-pawn.png",
  "e7": "black-pawn.png",
  "f7": "black-pawn.png",
  "g7": "black-pawn.png",
  "h7": "black-pawn.png",
};


function App() {
  const Coloring = (ver, hor) => {
    return (ver.charCodeAt(0) % 2 === hor % 2) ? "black" : "white";
  };

  return (
    <div className="App">
      {horizontalLine.map((horizontals) => (
        verticalLine.map((verticals) => {
          const id = `${verticals}${horizontals}`;
          const piece = pieces[id];
          return (
            <div
              className={`square ${Coloring(verticals, parseInt(horizontals))}`}
              key={id}
              id={id}
            >
              {piece && <img src={`./pieces-basic-png/${piece}`} alt={piece} />}
            </div>
          );
        })
      ))}
    </div>
  );
}

export default App;

and here is the css code:

.App{
  width: 700px;
  display: flex;
  flex-wrap: wrap;
}

.square{
  width: 85px;
  height: 85px;
  box-sizing: border-box;
}

.piece{
  width: 85px;
  height: 85px;
}

enter image description here
enter image description here

enter image description here

2

Answers


  1. Try to move ‘pieces-basic-png’ folder to public folder, and in src attribute use: ‘/pieces-basic-png/${piece}

    Login or Signup to reply.
  2. Image tag syntax may be wrong. You should give the image tag like below:

    <img src={require(`./pieces-basic-png/${piece}`)} alt={piece} />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search