ARTICLE AD BOX
This is the lab I am currently working on:
https://www.freecodecamp.org/learn/front-end-development-libraries-v9/lab-tic-tac-toe/build-a-tic-tac-toe-game
My code so far:
index.jsx
const { useState } = React; export function Board() { const [currentPlayer, setCurrentPlayer] = useState("X"); // Create sparse array containing 9 elements const boxes = new Array(9); return ( <div> <h1 style={{textAlign: "center"}}>Tic-Tac-Toe</h1> <h2 style={{textAlign: "center", fontWeight: "normal"}}>Next Player: {currentPlayer}</h2> <div className="grid-container"> { // I want to modify each element within the sparse array to add HTML markup boxes.map((item) => ( <div className="square"></div> )) } </div> </div> ); }styles.css
.grid-container { display: grid; grid-template-columns: auto auto auto; grid-template-rows: auto auto auto; padding: 10px; } .square { border: 1px solid black; padding: 10px; font-size: 30px; text-align: center; background-color: gray; }For the moment, I just need help trying to understand how I can render a box to the page multiple times without doing it manually. I have done exercises in the past where I use a .map() function on an array containing various objects that are then rendered to the page with their information. However, I just want an empty box within a 3x3 grid. I am unsure how I can accomplish that alongside ensuring it remains a flex-box layout. Should I simply create a sparse array and then reference their index as a unique identifier when employing the .map() callback function? So, I'd modify nine elements and render them to the page with the styling as shown in the image below.
I have looked at other questions on this site to see if there were other solutions to this problem, but it pertained to rendering a component multiple times or an array containing values such as objects. I may be looking at this the wrong way and can indeed utilize that same approach. Though I am unsure how I could get started.
Progress Made:
index.jsx
const { useState } = React; export function Board() { const [currentPlayer, setCurrentPlayer] = useState("X"); const [boxMark, setBoxMark] = useState(); const boxes = new Array(9).fill(undefined); function handleMove() { if (currentPlayer === "X") { setBoxMark("X"); setCurrentPlayer("Y"); } else { setBoxMark("Y"); setCurrentPlayer("X"); } } return ( <div> <h1 style={{textAlign: "center"}}>Tic-Tac-Toe</h1> <h2 style={{textAlign: "center", fontWeight: "normal"}}>Next Player: {currentPlayer}</h2> <div className="grid-container"> { boxes.map((item, index) => ( <button key={index} onClick={handleMove} role="button" className="square">{boxMark}</button> )) } </div> </div> ); }
