I’m new to React and I’m trying to grasp the broad strokes by building a simple minesweeper game. I’m able to render a 10×10 board (Grid), and reveal squares (Square). However, I’ve hit a wall with the step in which multiple squares are revealed with a single click.
The way I’ve written it (I think) requires a square component to know if the surrounding square components have a mine. How should I go about this? Or am I writing it in a way that isn’t really consistent with React’s intended use?
Code:
----------
Grid.js
----------
import React from 'react';
import Square from './Square';
export default function Grid(props) {
const grid = new Array(10);
for (let i = 0; i < 10; i++) {
grid[i] = new Array(10).fill(null);
}
return (
<div>
{
grid.map((row, x) => {
return (
<div key={x}>
{
row.map((col, y) => {
const randInt = Math.floor(Math.random() * 5);
return (
<Square
row={x}
col={y}
id={`square-${x}-${y}`}
key={`square-${x}-${y}`}
hasMine={randInt === 0}
/>
)
})
}
</div>
)
})
}
</div>
)
}
---------
Square.js
---------
export default function Square(props) {
function uncover(e) {
if (!props.hasMine && e.target.className !== 'white-square') {
e.target.className = 'white-square';
let right = document.getElementById(`square-${props.row}-${props.col + 1}`);
let bottomRight = document.getElementById(`square-${props.row + 1}-${props.col + 1}`);
let bottom = document.getElementById(`square-${props.row + 1}-${props.col}`);
let bottomLeft = document.getElementById(`square-${props.row + 1}-${props.col - 1}`);
let left = document.getElementById(`square-${props.row}-${props.col - 1}`);
let topLeft = document.getElementById(`square-${props.row - 1}-${props.col - 1}`);
let top = document.getElementById(`square-${props.row - 1}-${props.col}`);
let topRight = document.getElementById(`square-${props.row - 1}-${props.col + 1}`);
if (right) {
right.click();
}
if (bottomRight) {
bottomRight.click();
}
if (bottom) {
bottom.click();
}
if (bottomLeft) {
bottomLeft.click()
}
if (left) {
left.click()
}
if (topLeft) {
topLeft.click()
}
if (top) {
top.click()
}
if (topRight) {
topRight.click()
}
}
}
return (
<div
className={props.hasMine ? 'red-square' : 'grey-square'}
id={props.id}
onClick={uncover}
/>
)
}