Conway's Game of Life as a React web app
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Board.tsx 865B

12345678910111213141516171819202122232425262728293031323334353637
  1. import React, { useState } from 'react';
  2. import Cell from './Cell';
  3. interface Props {
  4. width?: number;
  5. height?: number;
  6. }
  7. const Board = (props: Props) => {
  8. const width = props.width ?? 5;
  9. const height = props.height ?? 5;
  10. const initialGrid: boolean[][] = Array(height).fill(Array(width).fill(false));
  11. const [grid, setGrid] = useState<boolean[][]>(initialGrid);
  12. const toggle = (x: number, y: number) => {
  13. const newGrid = [...grid];
  14. const newRow = [...newGrid[y]];
  15. newRow[x] = !newGrid[y][x];
  16. newGrid[y] = newRow;
  17. setGrid(newGrid);
  18. };
  19. return (
  20. <div className="board">
  21. {grid.map((row, y) => (
  22. <div className="row" key={y}>
  23. {row.map((cell, x) => (
  24. <Cell x={x} y={y} alive={cell} toggle={toggle} key={x} />
  25. ))}
  26. </div>
  27. ))}
  28. </div>
  29. );
  30. };
  31. export default Board;