How to write onClick function which remove squares from the board?

  javascript, onclick, reactjs

I’m trying to create a game: there is a board with colorful squares inside, user clicks on any square and if there are any squares in the same color on the left, right, top or bottom – all disappear. Squares which are above "fall down" to their place.

I have a Board.js component which generates a board with squares and there is onClick function which should remove squares in the same color. The problem is I don’t know what should I do now and how to write that function. I have index of any square and their rgb value in function arguments.

Board.js:

import React, { Component } from "react";

import { generateSquares } from "../../utils/squares";
import "./Board.css";

class Board extends Component {
  state = {
    squaresAmount: generateSquares(72),
    colorsAmount: 4
  };

  handleClick = (index, randomColor) => {
    // console.log(index);
    // console.log(randomColor);
  };

  render() {
    const { squaresAmount, colorsAmount } = this.state;

    const squares = squaresAmount.map((square, index) => {
      const randomColor =
        squaresAmount[Math.floor(Math.random() * colorsAmount)];
      return (
        <div
          key={square}
          className="square"
          style={{ background: randomColor }}
          value={randomColor}
          onClick={() => this.handleClick(index, randomColor)}
        ></div>
      );
    });
    console.log(squares);

    return <div className="squares">{squares}</div>;
  }
}

export default Board;

squares.js (which generate squares):

export const randomUpTo = (max) => {
  return Math.floor(Math.random() * max);
};

const randomColor = () => {
  const r = randomUpTo(255);
  const g = randomUpTo(255);
  const b = randomUpTo(255);
  return `rgb(${r}, ${g}, ${b})`;
};

export const generateSquares = (n) => {
  return Array.from(new Array(n), randomColor);
};

Anyone knows how to fill onClick function? Or maybe my idea is completly wrong and I should change something?

Source: Ask Javascript Questions

LEAVE A COMMENT