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( <div className='TileWhite'></div> ) } const AquaTile = () => { return( <div className='TileAqua'></div> ) } const ENUM_OBJECT = { whiteTile: <WhiteTile/>, aquaTile: <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(<Tile tileType={"whiteTile"} key={''}></Tile>); } else { coordinatesBoard.push(<Tile tileType={"aquaTile"} key={''}></Tile>); } } } return coordinatesBoard; } return(<div className="App"> {<RenderCoordinates/>} </div>) } export default ChessBoard;
I have tried using the map function before
const RenderTiles = () => { const cBoard = coordinatesBoard.map((xyCoordinates, index) => { if(index % 2) { return( <div className ="Tile1" key={index}> {xyCoordinates} </div> ) } else { return( <div className ="Tile2" key={index}> {xyCoordinates} </div> ) } }); 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(<Tile tileType={"whiteTile"} key={counter + 1}></Tile>);
I expect the counter to increment every time a tile is pushed onto the board please help.
P粉4516148342023-09-15 09:01:53
You can use a basic random string generator (not always guaranteed to be unique, but it is very random)
function randomString() { const possibleChars = 'abcxyz123' const length = 10 const randString = [] for (let i = 0; i <= length; i++) { const randomChar = possibleChars[Math.floor(Math.random() * possibleChars.length)] randString.push(randomChar) } return randString.join('') } console.log(randomString()) // "3zb1baxbbyy"