API Reference

Complete component documentation with interactive examples. Toggle any prop and see the board update in real time.

Interactive Playground

Toggle props and watch the board update live. The generated code below stays in sync.

Appearance

Layout & Display

Behavior

Generated Code
<Chessboard
  width={320}
  height={320}
  theme="brown"
  orientation="white"
  layout="horizontal"
  pgn="..."
  showMoveHistory={true}
  showNavigation={true}
  showBoardControls={true}
  showCoordinates={true}
  autoPromoteToQueen={false}
  enableKeyboardNavigation={true}
  onMove={(from, to, move) => {
    console.log(move.san);
  }}
/>

Chessboard

All-in-one convenience component. Wraps ChessProvider, Board, MoveHistory, Navigation, and BoardControls into a single element with a flat prop API.

Usage
import { Chessboard } from "@mdwebb/react-chess";
import "@mdwebb/react-chess/styles";

<Chessboard
  width={500}
  height={500}
  theme="brown"
  showMoveHistory={true}
  showNavigation={true}
  onMove={(from, to, move) => console.log(move.san)}
/>
PropTypeDefaultDescription
widthstring | number"400px"Board width
heightstring | number"400px"Board height
themeChessboardTheme"brown"Theme preset name or custom theme object
orientationPieceColor"white"Board orientation: "white" or "black"
layoutChessboardLayout"horizontal"Layout: "horizontal", "vertical", or "board-only"
fenstring"start"FEN string for initial position
pgnstringPGN string to load a game
showMoveHistorybooleanfalseDisplay the move history panel
showNavigationbooleanfalseDisplay navigation buttons (First/Prev/Next/Last)
showBoardControlsbooleanfalseDisplay board control buttons (flip, reset)
showCoordinatesbooleantrueShow a–1h / 1–8 coordinate labels
moveHistoryWidthstring | number"300px"Width of the move history panel
autoPromoteToQueenbooleanfalseAuto-promote pawns to queen without dialog
enableKeyboardNavigationbooleantrueEnable arrow key / Home / End navigation
draggableConfig['draggable']Chessground draggable configuration pass-through
movableConfig['movable']Chessground movable configuration pass-through
animationConfig['animation']Chessground animation configuration pass-through
classNamestringCSS class for the root container
styleCSSPropertiesInline styles for the root container
boardClassNamestringCSS class for the board wrapper
boardStyleCSSPropertiesInline styles for the board wrapper
moveHistoryClassNamestringCSS class for move history panel
navigationClassNamestringCSS class for navigation controls
childrenReactNodeAdditional children rendered after the board layout

Compound API

For custom layouts, compose Board, MoveHistory, Navigation, and BoardControls independently inside a ChessProvider. Each component reads from shared context.

Compound Usage
import {
  ChessProvider, Board,
  MoveHistory, Navigation, BoardControls,
} from "@mdwebb/react-chess";

<ChessProvider pgn={pgn} theme="blue">
  <div style={{ display: "flex", gap: "1rem" }}>
    <div>
      <Board width={400} height={400} />
      <Navigation />
      <BoardControls />
    </div>
    <MoveHistory />
  </div>
</ChessProvider>

ProviderChessProvider

Wraps compound components to provide shared chess game state and methods via React context. Use useChess() to access the context in custom components.

PropTypeDefaultDescription
children*ReactNodeChild components that consume chess context
fenstring"start"FEN string for initial position
pgnstringPGN string to load a game
orientationPieceColor"white"Initial board orientation
themeChessboardTheme"brown"Theme preset or custom theme object
autoPromoteToQueenbooleanfalseSkip promotion dialog, always promote to queen
enableKeyboardNavigationbooleantrueEnable keyboard navigation for child components

ComponentBoard

Renders the interactive chess board via Chessground. Must be inside a ChessProvider.

PropTypeDefaultDescription
widthstring | number"400px"Board width
heightstring | number"400px"Board height
showCoordinatesbooleantrueShow coordinate labels
draggableConfig['draggable']Chessground draggable config
movableConfig['movable']Chessground movable config
premovableConfig['premovable']Chessground premove config
drawableConfig['drawable']Chessground drawing config
highlightConfig['highlight']Chessground highlight config
animationConfig['animation']Chessground animation config
classNamestringCSS class for the board wrapper
styleCSSPropertiesInline styles for the board wrapper

ComponentMoveHistory

Scrollable move list with PGN metadata, annotations, and clickable moves for navigation. All props are optional when used inside ChessProvider.

PropTypeDefaultDescription
movesMove[]Move array (uses context if omitted)
onMoveClick(index: number) => voidCalled when a move is clicked
currentMoveIndexnumberIndex of the active move (-1 = start)
annotationsRecord<number, string>Move annotations (e.g. "!!", "?!")
commentsRecord<number, string>Move comments from PGN
variationsRecord<number, string[]>Variation lines
clockTimesRecord<number, string>Clock times per move
evaluationsRecord<number, string>Position evaluations per move
ravsRecord<number, RAV[]>Recursive annotation variations
headersPGNHeadersPGN header metadata (Event, Players, etc.)
widthstring | numberPanel width
classNamestringCSS class
styleCSSPropertiesInline styles

ComponentNavigation

First / Previous / Next / Last buttons for stepping through moves. Handlers default to context methods when omitted.

PropTypeDefaultDescription
onFirst() => voidCalled when First button clicked (uses context if omitted)
onPrevious() => voidCalled when Previous button clicked
onNext() => voidCalled when Next button clicked
onLast() => voidCalled when Last button clicked
canGoForwardbooleanEnable/disable next and last buttons
canGoBackwardbooleanEnable/disable first and previous buttons
classNamestringCSS class

ComponentBoardControls

Board control buttons (flip, etc.). Handlers default to context methods when omitted.

PropTypeDefaultDescription
onFlip() => voidCalled when flip button clicked (uses context if omitted)
showFlipButtonbooleantrueShow the flip board button
classNamestringCSS class

HookuseChess()

Access the full chess context inside any component within a ChessProvider. Returns game state, navigation methods, and configuration.

useChess() return value
import { useChess } from "@mdwebb/react-chess";

function MyComponent() {
  const {
    game,              // chess.js instance
    fen,               // current FEN
    orientation,       // "white" | "black"
    moveHistory,       // Move[]
    currentMoveIndex,  // number (-1 = start)
    isCheck,           // boolean
    isGameOver,        // boolean
    flipBoard,         // () => void
    makeMove,          // (from, to, promotion?) => boolean
    navigateToMove,    // (index) => void
    goFirst,           // () => void
    goPrevious,        // () => void
    goNext,            // () => void
    goLast,            // () => void
  } = useChess();
}

Callbacks

Event handlers available on both Chessboard and ChessProvider. All callbacks are optional and receive fully typed arguments.

PropTypeDefaultDescription
onMove(from: Key, to: Key, move: Move) => voidFires after every legal move. Receives origin/destination squares and the chess.js Move object.
onCheck(color: PieceColor) => voidFires when a side is placed in check. Receives the color in check.
onGameOver(result: GameOverResult) => voidFires on checkmate, stalemate, or draw. Result includes winner and reason.
onPromotion(from: Key, to: Key, piece: PromotionPiece) => voidFires after pawn promotion. Receives the chosen piece type.
onIllegalMove(from: string, to: string) => voidFires when a player attempts an illegal move.
onFlip(orientation: PieceColor) => voidFires when the board orientation changes.
onPositionChange(fen: string, moves: Move[]) => voidFires after any position update. Receives current FEN and full move history.
Callback example
<Chessboard
  onMove={(from, to, move) => {
    console.log(`${move.san} (${from} → ${to})`);
  }}
  onCheck={(color) => {
    console.log(`${color} is in check!`);
  }}
  onGameOver={(result) => {
    if (result.winner) {
      alert(`${result.winner} wins by ${result.reason}`);
    } else {
      alert(`Draw: ${result.reason}`);
    }
  }}
  onPromotion={(from, to, piece) => {
    console.log(`Promoted to ${piece}`);
  }}
/>

Ref API

Access imperative methods and underlying chess.js / chessground instances via a React ref.

Try imperative methods

Ref usage
const boardRef = useRef<ChessboardRef>(null);

<Chessboard ref={boardRef} pgn="..." />

// Imperative methods:
boardRef.current?.flip();
boardRef.current?.goNext();
boardRef.current?.goFirst();
boardRef.current?.navigateToMove(5);

// Access underlying instances:
boardRef.current?.game;  // chess.js
boardRef.current?.api;   // chessground
PropTypeDefaultDescription
apiApi | nullRaw Chessground API instance for advanced control
gameChess | nullchess.js game instance for direct game state access
flip()() => voidFlip the board orientation
navigateToMove(i)(index: number) => voidJump to a specific move by index
goFirst()() => voidNavigate to the starting position
goPrevious()() => voidNavigate to the previous move
goNext()() => voidNavigate to the next move
goLast()() => voidNavigate to the last move

Themes

Pass a preset name ("brown", "blue", "green", "gray") or a custom theme object. Use themePresets to access preset colors programmatically.

brown
blue
green
gray
Theme usage
// Use a preset
<Chessboard theme="blue" />

// Use a custom theme object
<Chessboard theme={{
  lightSquare: "#f0d9b5",
  darkSquare: "#b58863",
  selectedSquare: "rgba(20, 85, 30, 0.5)",
  lastMoveHighlight: "rgba(155, 199, 0, 0.41)",
  moveDestination: "rgba(20, 85, 30, 0.5)",
  checkHighlight: "rgba(255, 0, 0, 0.6)",
}} />

// Access preset values
import { themePresets } from "@mdwebb/react-chess";
console.log(themePresets.brown.darkSquare); // "#b58863"
PropTypeDefaultDescription
lightSquare*stringCSS color for light squares
darkSquare*stringCSS color for dark squares
selectedSquarestringHighlight color for the selected piece square
lastMoveHighlightstringHighlight color for the last move squares
moveDestinationstringIndicator color for legal move destinations
checkHighlightstringHighlight color when king is in check

Types Reference

All exported TypeScript types for full type safety.

Core types
type PieceColor = "white" | "black";
type PromotionPiece = "q" | "r" | "b" | "n";
type ChessboardLayout = "horizontal" | "vertical" | "board-only";
type ChessboardThemePreset = "brown" | "blue" | "green" | "gray";
type ChessboardTheme = ChessboardThemePreset | CustomTheme;
CustomTheme
interface CustomTheme {
  lightSquare: string;
  darkSquare: string;
  selectedSquare?: string;
  lastMoveHighlight?: string;
  moveDestination?: string;
  checkHighlight?: string;
}
GameOverResult
interface GameOverResult {
  winner?: PieceColor;
  reason:
    | "checkmate"
    | "stalemate"
    | "insufficient_material"
    | "threefold_repetition"
    | "fifty_move_rule"
    | "draw";
}
PGN types
interface PGNHeaders {
  White?: string;
  Black?: string;
  Date?: string;
  Event?: string;
  Site?: string;
  Result?: string;
  Round?: string;
  WhiteElo?: string;
  BlackElo?: string;
  ECO?: string;
  [key: string]: string | undefined;
}

interface PGNMetadata {
  annotations: Record<number, string>;
  comments: Record<number, string>;
  variations: Record<number, string[]>;
  clockTimes: Record<number, string>;
  evaluations: Record<number, string>;
  ravs: Record<number, { moves: string; comment?: string }[]>;
  headers: PGNHeaders;
}
ChessboardRef
interface ChessboardRef {
  api: Api | null;       // Chessground API
  game: Chess | null;    // chess.js instance
  flip: () => void;
  navigateToMove: (index: number) => void;
  goFirst: () => void;
  goPrevious: () => void;
  goNext: () => void;
  goLast: () => void;
}
Imports
// Components
import {
  Chessboard,
  ChessProvider,
  Board,
  MoveHistory,
  Navigation,
  BoardControls,
} from "@mdwebb/react-chess";

// Hook
import { useChess } from "@mdwebb/react-chess";

// Theme utilities
import {
  themePresets,
  resolveTheme,
  themeToCSSSVars,
  generateBoardSVG,
} from "@mdwebb/react-chess";

// Types
import type {
  ChessboardProps,
  ChessboardRef,
  ChessProviderProps,
  BoardProps,
  MoveHistoryProps,
  NavigationProps,
  BoardControlsProps,
  ChessboardTheme,
  ChessboardThemePreset,
  CustomTheme,
  ChessboardLayout,
  PieceColor,
  PromotionPiece,
  GameOverResult,
  PGNMetadata,
  PGNHeaders,
  ChessContextValue,
} from "@mdwebb/react-chess";