Skip to content

Instantly share code, notes, and snippets.

@morintd

morintd/app.tsx Secret

Created March 10, 2024 15:13
Show Gist options
  • Save morintd/61af36c8cfec25c75ba7796c49482306 to your computer and use it in GitHub Desktop.
Save morintd/61af36c8cfec25c75ba7796c49482306 to your computer and use it in GitHub Desktop.
import { useState } from "react";
import { Board } from "./components";
import "./app.css";
export function App() {
const [history, setHistory] = useState([Array(9).fill(null)]);
const [currentMove, setCurrentMove] = useState(0);
const xIsNext = currentMove % 2 === 0;
const currentSquares = history[currentMove];
function handlePlay(nextSquares: string[]) {
const nextHistory = [...history.slice(0, currentMove + 1), nextSquares];
setHistory(nextHistory);
setCurrentMove(nextHistory.length - 1);
}
function jumpTo(nextMove: number) {
setCurrentMove(nextMove);
}
const moves = history.map((_, move) => {
let description;
if (move > 0) {
description = "Go to move #" + move;
} else {
description = "Go to game start";
}
return (
<li key={move}>
<button onClick={() => jumpTo(move)}>{description}</button>
</li>
);
});
return (
<div className="game">
<div className="game-board">
<Board xIsNext={xIsNext} squares={currentSquares} onPlay={handlePlay} />
</div>
<div className="game-info">
<ol>{moves}</ol>
</div>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment