I'm new to building apps and coding, and as a side project I'm trying to make a chessboard using React and JavaScript. I'm currently trying to figure out a way to create a unique id key in the 2D for loop of the Chessboard component below:
This is the code for the Tile component
import './Tile.css'; const WhiteTile = () => { return( ) } const AquaTile = () => { return( ) } const ENUM_OBJECT = { whiteTile:, aquaTile: , }; function Tile({tileType}) { return ENUM_OBJECT[tileType] } export default Tile;
This is the code for the chessboard component
import React from 'react'; import '../ChessBoard/Chessboard.css' import Tile from './Tile'; function ChessBoard() { const xCoordinates = ["a", "b", "c", "d", "e", "f", "g", "h", "0"]; const yCoordinates = ["0", "1", "2", "3", "4", "5", "6", "7", "8"]; const coordinatesBoard = []; const RenderCoordinates = () => { for(let y = yCoordinates.length; y > 0; y--) { for(let x = 0; x < xCoordinates.length - 1; x++) { if(x % 2 === 0) { coordinatesBoard.push(); } else { coordinatesBoard.push( ); } } } return coordinatesBoard; } return( {) } export default ChessBoard;}
I have tried using the map function before
const RenderTiles = () => { const cBoard = coordinatesBoard.map((xyCoordinates, index) => { if(index % 2) { return({xyCoordinates}) } else { return({xyCoordinates}) } }); return cBoard }
Also studied useState
const [counter, setCounter] = useState(0); const increment = () => { setCounter(counter + 1); }
Tried to insert counter here but encountered infinite loop (from chessboard function)
coordinatesBoard.push();
I expect the counter to increment every time a tile is pushed onto the board please help.
You can use a basic random string generator (not always guaranteed to be unique, but it is very random)