### Install React Chessboard
Source: https://context7.com/clariity/react-chessboard/llms.txt
Install the react-chessboard package using npm, yarn, or pnpm.
```bash
npm install react-chessboard
# or
yarn add react-chessboard
# or
pnpm add react-chessboard
```
--------------------------------
### Clone and Install Dependencies
Source: https://github.com/clariity/react-chessboard/blob/main/docs/F_Contributing.mdx
Clone the forked repository, navigate into the directory, and install project dependencies using pnpm.
```bash
git clone https://github.com/YOUR-GITHUB-USERNAME/react-chessboard.git
cd react-chessboard
pnpm i
```
--------------------------------
### Install React Chessboard
Source: https://github.com/clariity/react-chessboard/blob/main/docs/A_GetStarted.mdx
Choose the package manager you prefer to install the react-chessboard package.
```bash
pnpm add react-chessboard
```
```bash
yarn add react-chessboard
```
```bash
npm i react-chessboard
```
--------------------------------
### Install React Chessboard
Source: https://github.com/clariity/react-chessboard/blob/main/README.md
Install the react-chessboard package using your preferred package manager.
```bash
pnpm add react-chessboard
# or
yarn add react-chessboard
# or
npm install react-chessboard
```
--------------------------------
### Example PieceDropHandlerArgs
Source: https://github.com/clariity/react-chessboard/blob/main/docs/E_FunctionsAndTypes.mdx
An example demonstrating how to structure the arguments for a piece drop handler. This shows a white pawn being moved from e2 to e4.
```typescript
const args: PieceDropHandlerArgs = {
piece: {
isSparePiece: false,
position: 'e2',
pieceType: 'wP',
},
sourceSquare: 'e2',
targetSquare: 'e4',
};
```
--------------------------------
### Custom Square Renderer Example
Source: https://github.com/clariity/react-chessboard/blob/main/docs/E_FunctionsAndTypes.mdx
An example of a custom square renderer. This implementation displays the square's coordinates in the top-right corner and renders any provided children (pieces).
```typescript
const squareRenderer = ({ square, children }) => (
{children}
{square}
);
```
--------------------------------
### Run Storybook for Testing
Source: https://github.com/clariity/react-chessboard/blob/main/docs/F_Contributing.mdx
Start Storybook to test your changes in an isolated environment.
```bash
pnpm storybook
```
--------------------------------
### Custom Piece Rendering Example
Source: https://github.com/clariity/react-chessboard/blob/main/docs/E_FunctionsAndTypes.mdx
An example of a custom piece rendering function for a white pawn ('wP'). It uses an SVG to draw the piece and accepts optional fill and style props.
```typescript
const customPieces: PieceRenderObject = {
wP: ({ fill, svgStyle }) => (
)
};
```
--------------------------------
### Conventional Commit: Documentation
Source: https://github.com/clariity/react-chessboard/blob/main/docs/F_Contributing.mdx
Example of a commit message for documentation changes.
```bash
git commit -m "docs: update installation instructions"
```
--------------------------------
### Conventional Commit: Feature
Source: https://github.com/clariity/react-chessboard/blob/main/docs/F_Contributing.mdx
Example of a commit message for adding a new feature.
```bash
git commit -m "feat: add support for custom board themes"
```
--------------------------------
### FenPieceString Example
Source: https://github.com/clariity/react-chessboard/blob/main/docs/E_FunctionsAndTypes.mdx
An example of using the FenPieceString type to declare a variable representing a white knight.
```typescript
const piece: FenPieceString = 'N'; // represents a white knight
```
--------------------------------
### options.position
Source: https://context7.com/clariity/react-chessboard/llms.txt
Sets the board position using either a FEN string or a `PositionDataType` object. Defaults to the standard starting position.
```APIDOC
## options.position
### Description
Accepts a FEN string or a `PositionDataType` object mapping square IDs to piece data; defaults to the standard starting position.
### Usage
```tsx
import { useState } from 'react';
import { Chess } from 'chess.js';
import { Chessboard } from 'react-chessboard';
function App() {
const [game] = useState(new Chess());
return (
{/* FEN string */}
{/* Position object */}
);
}
```
```
--------------------------------
### Implement Click-to-Move Interaction
Source: https://context7.com/clariity/react-chessboard/llms.txt
Use `options.onSquareClick` with `allowDragging: false` to create a click-based move interface. This example highlights possible moves and handles move execution.
```tsx
import { useRef, useState } from 'react';
import { Chess, Square } from 'chess.js';
import { Chessboard, SquareHandlerArgs } from 'react-chessboard';
export function ClickToMove() {
const chessGameRef = useRef(new Chess());
const game = chessGameRef.current;
const [position, setPosition] = useState(game.fen());
const [moveFrom, setMoveFrom] = useState('');
const [optionSquares, setOptionSquares] = useState>({});
function getMoveOptions(square: Square) {
const moves = game.moves({ square, verbose: true });
if (!moves.length) { setOptionSquares({}); return false; }
const highlights: Record = {};
for (const m of moves) {
highlights[m.to] = {
background: game.get(m.to)
? 'radial-gradient(circle, rgba(0,0,0,.1) 85%, transparent 85%)'
: 'radial-gradient(circle, rgba(0,0,0,.1) 25%, transparent 25%)',
borderRadius: '50%',
};
}
highlights[square] = { background: 'rgba(255,255,0,0.4)' };
setOptionSquares(highlights);
return true;
}
function onSquareClick({ square, piece }: SquareHandlerArgs) {
if (!moveFrom && piece) {
if (getMoveOptions(square as Square)) setMoveFrom(square);
return;
}
const moves = game.moves({ square: moveFrom as Square, verbose: true });
const found = moves.find((m) => m.from === moveFrom && m.to === square);
if (!found) { setMoveFrom(getMoveOptions(square as Square) ? square : ''); return; }
try {
game.move({ from: moveFrom, to: square, promotion: 'q' });
setPosition(game.fen());
} catch { /* invalid */ }
setMoveFrom('');
setOptionSquares({});
}
return (
);
}
```
--------------------------------
### Default Chessboard Component
Source: https://github.com/clariity/react-chessboard/blob/main/docs/B_BasicExamples.mdx
Shows the basic instantiation of the chessboard component. This serves as a starting point for customization.
```jsx
import React from 'react';
import { Chessboard } from 'react-chessboard';
function App() {
return ;
}
export default App;
```
--------------------------------
### Mini Puzzles Implementation
Source: https://github.com/clariity/react-chessboard/blob/main/docs/C_AdvancedExamples.mdx
Demonstrates how to create a mini puzzle using React Chessboard, inspired by 'mate in two' puzzles. This example highlights the component's flexibility for non-standard boards and custom game logic.
```typescript
import {
Chessboard,
COLOR_MODE,
GameState,
Piece
} from '@chessboard/react-chessboard';
import React from 'react';
const MiniPuzzles = () => {
const [gameState, setGameState] = React.useState(null);
const onDrop = React.useCallback(
(move: string) => {
console.log(move);
},
[]
);
const onSquareClick = React.useCallback(
(square: string) => {
console.log(square);
},
[]
);
const onPromotionPieceSelect = React.useCallback(
(piece: Piece, move: string) => {
console.log(piece, move);
},
[]
);
return (
);
};
export default MiniPuzzles;
```
--------------------------------
### Implement Custom Piece Promotion Dialog in React Chessboard
Source: https://context7.com/clariity/react-chessboard/llms.txt
Intercept promotion moves using `onPieceDrop` to render a custom promotion picker as a React overlay. This example shows how to handle the promotion logic before it reaches the game engine.
```tsx
import { useRef, useState } from 'react';
import { Chess, Square, PieceSymbol } from 'chess.js';
import {
Chessboard,
chessColumnToColumnIndex,
defaultPieces,
PieceDropHandlerArgs,
PieceRenderObject,
} from 'react-chessboard';
export function PromotionExample() {
const chessGameRef = useRef(new Chess('8/P7/7K/8/8/8/8/k7 w - - 0 1'));
const game = chessGameRef.current;
const [position, setPosition] = useState(game.fen());
const [promotionMove, setPromotionMove] = useState | null>(null);
function onPieceDrop({ sourceSquare, targetSquare }: PieceDropHandlerArgs) {
if (!targetSquare) return false;
if (targetSquare.match(/\d+$/)?.[0] === '8') {
const possible = game.moves({ square: sourceSquare as Square });
if (possible.some((m) => m.startsWith(`${targetSquare}=`))) {
setPromotionMove({ sourceSquare, targetSquare });
}
return true; // hold off animating
}
try {
game.move({ from: sourceSquare, to: targetSquare });
setPosition(game.fen());
return true;
} catch { return false; }
}
function onPromotionPieceSelect(piece: PieceSymbol) {
try {
game.move({ from: promotionMove!.sourceSquare, to: promotionMove!.targetSquare as Square, promotion: piece });
setPosition(game.fen());
} catch { /* noop */ }
setPromotionMove(null);
}
const squareWidth =
document.querySelector('[data-column="a"][data-row="1"]')?.getBoundingClientRect()?.width ?? 50;
const left = promotionMove?.targetSquare
? squareWidth * chessColumnToColumnIndex(promotionMove.targetSquare[0], 8, 'white')
: 0;
return (
{promotionMove && (
{(['q', 'r', 'n', 'b'] as PieceSymbol[]).map((p) => (
))}
)}
);
}
```
--------------------------------
### Board Editor with Spare Pieces using ChessboardProvider
Source: https://context7.com/clariity/react-chessboard/llms.txt
Use `ChessboardProvider` to share context with `SparePiece` components for creating board editors. This setup allows pieces to be dragged from spare piece areas onto the board.
```tsx
import { useEffect, useRef, useState } from 'react';
import { Chess, Color, PieceSymbol, Square } from 'chess.js';
import {
Chessboard,
ChessboardProvider,
SparePiece,
defaultPieces,
PieceDropHandlerArgs,
} from 'react-chessboard';
export function BoardEditor() {
const chessGameRef = useRef(
new Chess('8/8/8/8/8/8/8/8 w - - 0 1', { skipValidation: true }),
);
const game = chessGameRef.current;
const [position, setPosition] = useState(game.fen());
const [squareWidth, setSquareWidth] = useState(null);
useEffect(() => {
const sq = document.querySelector('[data-column="a"][data-row="1"]')?.getBoundingClientRect();
setSquareWidth(sq?.width ?? null);
}, []);
function onPieceDrop({ piece, sourceSquare, targetSquare }: PieceDropHandlerArgs) {
const color = piece.pieceType[0] as Color;
const type = piece.pieceType[1].toLowerCase() as PieceSymbol;
if (!targetSquare) {
game.remove(sourceSquare as Square);
setPosition(game.fen());
return true;
}
if (!piece.isSparePiece) game.remove(sourceSquare as Square);
const ok = game.put({ color, type }, targetSquare as Square);
if (!ok) { alert('Cannot place a second king of the same color'); return false; }
setPosition(game.fen());
return true;
}
const whitePieces = Object.keys(defaultPieces).filter((p) => p[0] === 'w');
const blackPieces = Object.keys(defaultPieces).filter((p) => p[0] === 'b');
return (
{squareWidth && (
{blackPieces.map((t) => (
))}
)}
{squareWidth && (
{whitePieces.map((t) => (
))}
)}
);
}
```
--------------------------------
### Update react-chessboard Dependency
Source: https://github.com/clariity/react-chessboard/blob/main/docs/G_UpgradeToV5.mdx
Use your preferred package manager to install the latest version of react-chessboard.
```bash
pnpm i react-chessboard@latest
# or
yarn add react-chessboard@latest
# or
npm i react-chessboard@latest
```
--------------------------------
### Set Chessboard Position with FEN or Object
Source: https://context7.com/clariity/react-chessboard/llms.txt
Configure the chessboard's starting position using either a FEN string or a position object. The `chess.js` library is commonly used to generate FEN strings.
```tsx
import { useState } from 'react';
import { Chess } from 'chess.js';
import { Chessboard } from 'react-chessboard';
function App() {
const [game] = useState(new Chess());
return (
{/* FEN string */}
{/* Position object */}
);
}
```
--------------------------------
### onPieceDrag
Source: https://github.com/clariity/react-chessboard/blob/main/docs/D_OptionsApi.mdx
Handler for starting to drag a piece.
```APIDOC
## onPieceDrag
### Description
Handler for starting to drag a piece.
### Method
Callback Function
### Parameters
- **piece**: The dragged piece.
- **sourceSquare**: The square the piece was dragged from.
- **orientation**: The orientation of the board ('white' or 'black').
### Response
- **void**: This handler does not return a value.
```
--------------------------------
### Quick Start React Chessboard Component
Source: https://github.com/clariity/react-chessboard/blob/main/README.md
Import and render the Chessboard component in your React application. Configuration options can be passed via the 'options' prop.
```tsx
import { Chessboard } from 'react-chessboard';
function App() {
const chessboardOptions = {
// your config options here
};
return ;
```
--------------------------------
### Conventional Commit: Bug Fix
Source: https://github.com/clariity/react-chessboard/blob/main/docs/F_Contributing.mdx
Example of a commit message for fixing a bug.
```bash
git commit -m "fix: fix piece dragging on mobile devices"
```
--------------------------------
### Handle Piece Drops with onPieceDrop
Source: https://context7.com/clariity/react-chessboard/llms.txt
Implement drag-and-drop functionality by providing an `onPieceDrop` handler. Return `true` to confirm the move; return `false` to revert it. This example integrates with `chess.js` to validate moves and includes logic for a random opponent move.
```tsx
import { useRef, useState } from 'react';
import { Chess } from 'chess.js';
import { Chessboard, PieceDropHandlerArgs } from 'react-chessboard';
export function PlayVsRandom() {
const chessGameRef = useRef(new Chess());
const game = chessGameRef.current;
const [position, setPosition] = useState(game.fen());
function makeRandomMove() {
if (game.isGameOver()) return;
const moves = game.moves();
game.move(moves[Math.floor(Math.random() * moves.length)]);
setPosition(game.fen());
}
function onPieceDrop({ sourceSquare, targetSquare }: PieceDropHandlerArgs) {
if (!targetSquare) return false;
try {
game.move({ from: sourceSquare, to: targetSquare, promotion: 'q' });
setPosition(game.fen());
setTimeout(makeRandomMove, 500);
return true;
} catch {
return false; // invalid move — board reverts automatically
}
}
return (
);
}
```
--------------------------------
### Highlight Squares on Hover with `onMouseOverSquare`
Source: https://context7.com/clariity/react-chessboard/llms.txt
Use `onMouseOverSquare` and `onMouseOutSquare` to highlight potential moves when hovering over a square. This example demonstrates highlighting all legal moves from a hovered square.
```tsx
import { useState } from 'react';
import { Chess, Square } from 'chess.js';
import { Chessboard, SquareHandlerArgs } from 'react-chessboard';
export function HoverHighlight() {
const [game] = useState(new Chess());
const [hoverSquares, setHoverSquares] = useState>({});
function onMouseOverSquare({ square }: SquareHandlerArgs) {
const moves = game.moves({ square: square as Square, verbose: true });
const hl: Record = {};
for (const m of moves) {
hl[m.to] = { backgroundColor: 'rgba(0,255,0,0.2)' };
}
setHoverSquares(hl);
}
return (
setHoverSquares({}),
}}
/>
);
}
```
--------------------------------
### Conventional Commit: Breaking Change
Source: https://github.com/clariity/react-chessboard/blob/main/docs/F_Contributing.mdx
Example of a commit message for a breaking change, indicated by an exclamation mark.
```bash
git commit -m "feat!: change board orientation API"
```
--------------------------------
### Prepare for Next Contribution
Source: https://github.com/clariity/react-chessboard/blob/main/docs/F_Contributing.mdx
Switch to the main branch, pull the latest changes from upstream, and create a new branch for subsequent contributions.
```bash
git checkout main
git pull upstream main
git checkout -b your-new-branch-name
```
--------------------------------
### Analysis Board Implementation
Source: https://github.com/clariity/react-chessboard/blob/main/docs/C_AdvancedExamples.mdx
Shows how to implement an analysis board using React Chessboard and a chess engine like Stockfish. Requires a Web Worker and specific engine files.
```typescript
import {
BoardControls,
Chessboard,
COLOR_MODE,
GameState,
GameStatus,
Piece
} from '@chessboard/react-chessboard';
import React from 'react';
import { Engine } from './stockfish/engine';
const AnalysisBoard = () => {
const [engine, setEngine] = React.useState(null);
const [bestMove, setBestMove] = React.useState(null);
const [evaluation, setEvaluation] = React.useState(null);
const [gameState, setGameState] = React.useState(null);
React.useEffect(() => {
const engine = new Engine();
setEngine(engine);
engine.onmessage = (event) => {
const { bestMove, evaluation } = event.data;
setBestMove(bestMove);
setEvaluation(evaluation);
};
return () => {
engine.terminate();
};
}, []);
const onDrop = React.useCallback(
(move: string) => {
if (!engine) return;
engine.postMessage(`position fen ${gameState?.fen}`);
engine.postMessage(`go depth 10`);
},
[engine, gameState]
);
const onSquareClick = React.useCallback(
(square: string) => {
if (!engine) return;
engine.postMessage(`position fen ${gameState?.fen}`);
engine.postMessage(`go depth 10`);
},
[engine, gameState]
);
const onPromotionPieceSelect = React.useCallback(
(piece: Piece, move: string) => {
if (!engine) return;
engine.postMessage(`position fen ${gameState?.fen}`);
engine.postMessage(`go depth 10`);
},
[engine, gameState]
);
return (
);
};
export default AnalysisBoard;
```
--------------------------------
### Basic Chessboard Usage
Source: https://github.com/clariity/react-chessboard/blob/main/docs/A_GetStarted.mdx
Import and render the Chessboard component, configuring it with an options object. Refer to the Options API documentation for available configurations.
```tsx
import { Chessboard } from 'react-chessboard';
function App() {
const chessboardOptions = {
// your config options here
};
return ;
}
```
--------------------------------
### Arrow Type Definition
Source: https://github.com/clariity/react-chessboard/blob/main/docs/E_FunctionsAndTypes.mdx
Defines the structure for an arrow on the chessboard, including start and end squares and color.
```typescript
type Arrow = {
startSquare: string; // e.g. "a8"
endSquare: string; // e.g. "a7"
color: string; // e.g. "#000000"
};
```
```typescript
const arrow: Arrow = {
startSquare: 'e2',
endSquare: 'e4',
color: '#000000',
};
```
--------------------------------
### Board Orientation
Source: https://github.com/clariity/react-chessboard/blob/main/docs/D_OptionsApi.mdx
Configure the board's orientation, allowing it to be viewed from black's perspective.
```APIDOC
### `options.boardOrientation`
Controls the orientation of the board. When set to "black", the board is flipped so black pieces are at the bottom.
**Default value:** `"white"`
**TypeScript type:** `"white" | "black"`
**Standard use case:** Allowing players to view the board from the perspective of the pieces they are playing with.
```
--------------------------------
### Arrow Options
Source: https://github.com/clariity/react-chessboard/blob/main/docs/D_OptionsApi.mdx
Customize the appearance and behavior of arrows drawn on the chessboard, including length, width, opacity, and starting position.
```APIDOC
## Arrow Options
### Description
Controls the styling and behavior of arrows on the chessboard.
### Properties
- `arrowLengthReducerDenominator` (number): Controls how much the arrow length is reduced. Lower values mean greater reduction.
- `sameTargetArrowLengthReducerDenominator` (number): Similar to `arrowLengthReducerDenominator` but specifically for arrows targeting the same square, with a greater reduction to prevent overlaps.
- `arrowStartOffset` (number): Controls the starting position of the arrow from the center of the start square, as a fraction of the square width (0 = center, 0.5 = edge).
- `arrowWidthDenominator` (number): Controls the width of the arrow. Lower values mean greater width.
- `activeArrowWidthMultiplier` (number): Sets the multiplier for the arrow width when it is being drawn.
- `opacity` (number): Controls the opacity of arrows when not being drawn.
- `activeOpacity` (number): Controls the opacity of arrows when they are being drawn.
### Default Value
```json
{
"color": "#ffaa00",
"secondaryColor": "#4caf50",
"tertiaryColor": "#f44336",
"arrowLengthReducerDenominator": 8,
"sameTargetArrowLengthReducerDenominator": 4,
"arrowWidthDenominator": 5,
"activeArrowWidthMultiplier": 0.9,
"opacity": 0.65,
"activeOpacity": 0.5,
"arrowStartOffset": 0
}
```
### TypeScript Type
```typescript
{
color: string,
secondaryColor: string,
tertiaryColor: string,
arrowLengthReducerDenominator: number,
sameTargetArrowLengthReducerDenominator: number,
arrowWidthDenominator: number,
activeArrowWidthMultiplier: number,
opacity: number,
activeOpacity: number
arrowStartOffset: number,
}
```
```
--------------------------------
### Using Spare Pieces with React Chessboard
Source: https://github.com/clariity/react-chessboard/blob/main/docs/B_BasicExamples.mdx
Demonstrates how to implement spare pieces functionality, allowing pieces to be dragged onto and off the board. Requires wrapping the chessboard and spare pieces within `ChessboardProvider`. All chessboard props should be passed via the `options` prop of `ChessboardProvider`.
```jsx
import React, { useState, useCallback } from 'react';
import { Chessboard, ChessboardProvider } from 'react-chessboard';
function SparePieces() {
const [boardPosition, setBoardPosition] = useState(
'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
);
const onPieceDrop = useCallback(
(sourceSquare, targetSquare) => {
// If the piece is dropped on the board
if (targetSquare) {
setBoardPosition((prevBoardPosition) => {
const fen = prevBoardPosition;
const fenArray = fen.split(' ');
const board = fenArray[0].split('/');
// Remove the piece from the source square
const newBoard = board.map((row) =>
row.replace(/./g, (char) => {
if (char.match(/[a-zA-Z]/)) {
const square = `${String.fromCharCode(97 + row.indexOf(char))}${8 - board.indexOf(row)}`;
if (square === sourceSquare) return '.';
}
return char;
})
);
// Add the piece to the target square
const targetRow = 8 - parseInt(targetSquare.slice(1));
const targetCol = targetSquare.charCodeAt(0) - 97;
const targetRowArray = newBoard[targetRow].split('');
targetRowArray[targetCol] = sourceSquare.slice(-1); // Assuming sourceSquare has the piece type at the end
newBoard[targetRow] = targetRowArray.join('');
fenArray[0] = newBoard.join('/');
return fenArray.join(' ');
});
} else {
// If the piece is dropped off the board
setBoardPosition((prevBoardPosition) => {
const fen = prevBoardPosition;
const fenArray = fen.split(' ');
const board = fenArray[0].split('/');
// Remove the piece from the source square
const newBoard = board.map((row) =>
row.replace(/./g, (char) => {
if (char.match(/[a-zA-Z]/)) {
const square = `${String.fromCharCode(97 + row.indexOf(char))}${8 - board.indexOf(row)}`;
if (square === sourceSquare) return '.';
}
return char;
})
);
fenArray[0] = newBoard.join('/');
return fenArray.join(' ');
});
}
return true;
},
[]
);
return (
);
}
export default SparePieces;
```
--------------------------------
### options.onPieceDrag
Source: https://github.com/clariity/react-chessboard/blob/main/docs/D_OptionsApi.mdx
Callback function triggered when a piece drag operation starts. Useful for implementing custom drag and drop behavior or validation.
```APIDOC
## options.onPieceDrag
### Description
Callback function triggered when a piece drag operation starts.
### TypeScript type
```typescript
({ isSparePiece: boolean, piece: { pieceType: string }, square: string | null }) => void;
```
### Default value
`undefined`
```
--------------------------------
### Create a New Branch
Source: https://github.com/clariity/react-chessboard/blob/main/docs/F_Contributing.mdx
Create a new branch for your feature or bug fix.
```bash
git checkout -b your-branch-name
```
--------------------------------
### Default Arrow Options
Source: https://github.com/clariity/react-chessboard/blob/main/docs/D_OptionsApi.mdx
These are the default values for arrow customization. Adjust these to change the color, length, width, opacity, and starting offset of arrows.
```tsx
{
color: "#ffaa00", // yellow
secondaryColor: "#4caf50", // green
tertiaryColor: "#f44336", // red
arrowLengthReducerDenominator: 8,
sameTargetArrowLengthReducerDenominator: 4,
arrowWidthDenominator: 5,
activeArrowWidthMultiplier: 0.9,
opacity: 0.65,
activeOpacity: 0.5,
arrowStartOffset: 0,
}
```
--------------------------------
### Push Changes and Set Upstream
Source: https://github.com/clariity/react-chessboard/blob/main/docs/F_Contributing.mdx
Stage all changes, commit them with a descriptive message, and push to your remote branch, setting the upstream.
```bash
git add .
git commit -m "feat: cool new feature"
git push --set-upstream origin your-branch-name
```
--------------------------------
### Using React Chessboard with chess.js
Source: https://github.com/clariity/react-chessboard/blob/main/docs/B_BasicExamples.mdx
Demonstrates integrating React Chessboard with the chess.js library to manage game logic. It uses `onPieceDrop` to handle moves and `position` to update the board. A `chessGameRef` is crucial to prevent stale closures when updating game state within callbacks.
```jsx
import React, { useRef, useState, useCallback } from 'react';
import { Chessboard } from 'react-chessboard';
import { Chess } from 'chess.js';
function PlayVsRandom() {
const chessGameRef = useRef(null);
const [boardPosition, setBoardPosition] = useState('start');
const safeGameMutate = useCallback((modify) => {
setBoardPosition((prevBoardPosition) => {
const board = chessGameRef.current;
const newGame = { ...board };
modify(newGame);
chessGameRef.current = newGame;
return newGame.fen();
});
}, []);
const onPieceDrop = useCallback(
(sourceSquare, targetSquare) => {
let move = null;
safeGameMutate((game) => {
move = game.move({
from: sourceSquare,
to: targetSquare,
promotion: 'q', // always promote to a queen for example simplicity
});
});
if (move === null) return false; // illegal move
return true;
},
[safeGameMutate]
);
return (
);
}
export default PlayVsRandom;
```
--------------------------------
### Get Position Updates with `getPositionUpdates`
Source: https://context7.com/clariity/react-chessboard/llms.txt
Calculates the difference between two board positions to determine which pieces have moved. This utility is primarily used internally to animate piece movements.
```typescript
import { fenStringToPositionObject, getPositionUpdates } from 'react-chessboard';
const before = fenStringToPositionObject('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR', 8, 8);
const after = fenStringToPositionObject('rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR', 8, 8);
const updates = getPositionUpdates(before, after, 8, 'white');
// { e2: 'e4' }
```
--------------------------------
### Get Square Pixel Coordinates with `getRelativeCoords`
Source: https://context7.com/clariity/react-chessboard/llms.txt
Retrieves the `{ x, y }` pixel coordinates for the center of a given square, relative to the board's top-left corner. This is useful for overlaying custom graphics or annotations.
```typescript
import { getRelativeCoords } from 'react-chessboard';
const coords = getRelativeCoords('white', 400, 8, 8, 'e4');
// { x: 225, y: 200 } (centre of the e4 square on a 400px board)
const coords2 = getRelativeCoords('black', 400, 8, 8, 'e4');
// Flipped for black orientation
```
--------------------------------
### Chess notation conversion utilities
Source: https://context7.com/clariity/react-chessboard/llms.txt
Helper functions for translating between zero-based array indices and algebraic chess notation, accounting for board orientation.
```APIDOC
## Chess notation conversion utilities
Four helper functions for translating between zero-based array indices and algebraic chess notation, accounting for board orientation.
```typescript
import {
rowIndexToChessRow,
columnIndexToChessColumn,
chessColumnToColumnIndex,
chessRowToRowIndex,
} from 'react-chessboard';
rowIndexToChessRow(0, 8, 'white'); // '8' (top row = rank 8 in white view)
rowIndexToChessRow(0, 8, 'black'); // '1' (top row = rank 1 in black view)
columnIndexToChessColumn(0, 8, 'white'); // 'a'
columnIndexToChessColumn(0, 8, 'black'); // 'h' (mirrored)
chessColumnToColumnIndex('a', 8, 'white'); // 0
chessColumnToColumnIndex('a', 8, 'black'); // 7
chessRowToRowIndex('1', 8, 'white'); // 7 (rank 1 is the bottom row)
chessRowToRowIndex('1', 8, 'black'); // 0
```
```
--------------------------------
### showNotation
Source: https://github.com/clariity/react-chessboard/blob/main/docs/D_OptionsApi.mdx
Controls whether board coordinates (ranks and files) are displayed. Hide for a cleaner look or when space is limited.
```APIDOC
## showNotation
### Description
Controls whether board coordinates (ranks and files) are displayed. Hide for a cleaner look or when space is limited.
### Default value
`true`
### Type
`boolean`
```
--------------------------------
### options.lightSquareNotationStyle
Source: https://github.com/clariity/react-chessboard/blob/main/docs/D_OptionsApi.mdx
Defines the styling for chess notation displayed on light squares. Similar to `darkSquareNotationStyle`, it aids readability and can be overridden by `alphaNotationStyle` and `numericNotationStyle`.
```APIDOC
## options.lightSquareNotationStyle
### Description
Controls the styling of notation on light squares. If you wish to instead hide the notation, set [`showNotation`](#optionsshownotation) to `false`.
This is separate from the [`alphaNotationStyle`](#optionsalphanotationstyle) prop, which controls the styling of the notation on all alpha squares.
[`alphaNotationStyle`](#optionsalphanotationstyle) and [`numericNotationStyle`](#optionsnumericnotationstyle) will take precedence over this style for any clashing properties.
### TypeScript type
`React.CSSProperties`
### Default value
```tsx
{
color: "#B58863",
}
```
```
--------------------------------
### Theming Chessboard with Style Options
Source: https://context7.com/clariity/react-chessboard/llms.txt
Customize the visual appearance of the chessboard by overriding styles for dark squares, light squares, and the board container using `options.darkSquareStyle`, `options.lightSquareStyle`, and `options.boardStyle`.
```tsx
import { Chessboard } from 'react-chessboard';
export function WoodTheme() {
return (
);
}
```
--------------------------------
### options.numericNotationStyle
Source: https://github.com/clariity/react-chessboard/blob/main/docs/D_OptionsApi.mdx
Controls the styling of the numeric notation (1-8) on the board. Can be used in conjunction with other notation style props for different square colors.
```APIDOC
## options.numericNotationStyle
### Description
Controls the styling of the numeric notation (1-8) on the board. If you wish to instead hide the notation, set [`showNotation`](#optionsshownotation) to `false`.
If you wish to display different styles of notation on different coloured squares, you can use the [`darkSquareNotationStyle`](#optionsdarksquarenotationstyle) and [`lightSquareNotationStyle`](#optionslightsquarenotationstyle) props.
### TypeScript type
`React.CSSProperties`
### Default value
```json
{
"fontSize": "13px",
"position": "absolute",
"top": 2,
"left": 2,
"userSelect": "none"
}
```
```
--------------------------------
### showNotation
Source: https://github.com/clariity/react-chessboard/blob/main/docs/D_OptionsApi.mdx
Controls whether the algebraic notation (ranks and files) is displayed on the board.
```APIDOC
## showNotation
### Description
Controls whether board notation is displayed.
### Type
Boolean
### Default
`true`
```
--------------------------------
### Chess Notation Conversion Utilities
Source: https://context7.com/clariity/react-chessboard/llms.txt
Provides four helper functions to translate between zero-based array indices and algebraic chess notation, correctly handling board orientation for both white and black perspectives.
```typescript
import {
rowIndexToChessRow,
columnIndexToChessColumn,
chessColumnToColumnIndex,
chessRowToRowIndex,
} from 'react-chessboard';
rowIndexToChessRow(0, 8, 'white'); // '8' (top row = rank 8 in white view)
rowIndexToChessRow(0, 8, 'black'); // '1' (top row = rank 1 in black view)
columnIndexToChessColumn(0, 8, 'white'); // 'a'
columnIndexToChessColumn(0, 8, 'black'); // 'h' (mirrored)
chessColumnToColumnIndex('a', 8, 'white'); // 0
chessColumnToColumnIndex('a', 8, 'black'); // 7
chessRowToRowIndex('1', 8, 'white'); // 7 (rank 1 is the bottom row)
chessRowToRowIndex('1', 8, 'black'); // 0
```
--------------------------------
### Component
Source: https://context7.com/clariity/react-chessboard/llms.txt
The primary component for rendering an interactive chessboard. All configuration is passed through the `options` prop.
```APIDOC
## Chessboard Component
### Description
The primary component that renders a fully interactive chessboard; all configuration is passed through the `options` prop.
### Usage
```tsx
import { Chessboard } from 'react-chessboard';
function App() {
return (
);
}
```
```
--------------------------------
### Basic Chessboard Component Usage
Source: https://context7.com/clariity/react-chessboard/llms.txt
Render a basic, interactive chessboard component. Ensure the parent container has defined dimensions.
```tsx
import { Chessboard } from 'react-chessboard';
function App() {
return (
);
}
```
--------------------------------
### squareStyles
Source: https://github.com/clariity/react-chessboard/blob/main/docs/D_OptionsApi.mdx
Allows applying custom styles to specific squares.
```APIDOC
## squareStyles
### Description
Object mapping squares to custom styles.
### Type
Object
### Example
```javascript
{
'a1': { backgroundColor: 'red' },
'h8': { border: '2px solid blue' }
}
```
```