How to create unique keys in a 2D array of a checkerboard using React and JavaScript
P粉512729862
P粉512729862 2023-09-14 12:45:45
0
1
492

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.

P粉512729862
P粉512729862

reply all (1)
P粉451614834

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"
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!