I was working on a project to build a simple UI of chessboard using react for practice. I have encountered a problem where I am unable to render a given piece on a specific tile. Can anyone help me on where the potential issue may lie? I have made sure the image path is correct. It is located in the images folder inside the public folder.
PS: I am a beginner, I don’t know much.
//Typescript for react component
import './chessboard.css';
import Tile from "../Tiles/tile";
interface piece {
image?: string;
x: number;
y: number;
}
const pieces: piece[] = [];
const horizontalAxis = ["a", "b", "c", "d", "e", "f", "g", "h"];
const verticalAxis = [1, 2, 3, 4, 5, 6, 7, 8];
pieces.push({ image: "/images/black_pawn.png", x: 0, y: 1 });
export default function Chessboard() {
let board = [];
for (let j = verticalAxis.length - 1; j >= 0; j--) {
for (let i = 0; i < horizontalAxis.length; i++) {
const number = i + j + 2;
let image = undefined;
pieces.forEach(p => {
if (p.x === i && p.y === j) {
image = p.image;
}
});
board.push(<Tile image={image} number={number} />);
}
}
return <div id="chessboard">{board}</div>;
}
//TypeScript for tile component
import './tile.css';
interface props{
image?: string;
number: number;
}
export default function Tile({image, number}: props){
if(number%2===0){
return (<div className="tile black-tile"></div>)
}else{
return (<div className="tile white-tile"></div>)
}
}
>Solution :
It looks like the issue is with the Tile component where you’re not actually using the image prop that’s being passed down. To render the chess piece on the tile, you need to modify the Tile component to display the image if it exists.
Updated Tile Component (tile.tsx)
import './tile.css';
interface props {
image?: string;
number: number;
}
export default function Tile({ image, number }: props) {
const tileClass = number % 2 === 0 ? "tile black-tile" : "tile white-tile";
return (
<div className={tileClass}>
{image && <img src={image} alt="chess piece" className="piece-image" />}
</div>
);
}
Updated CSS (tile.css)
.piece-image {
width: 100%;
height: 100%;
object-fit: contain;
}