//00api_reference

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
pgnstring—PGN 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
classNamestring—CSS class for the root container
styleCSSProperties—Inline styles for the root container
boardClassNamestring—CSS class for the board wrapper
boardStyleCSSProperties—Inline styles for the board wrapper
moveHistoryClassNamestring—CSS class for move history panel
navigationClassNamestring—CSS class for navigation controls
childrenReactNode—Additional 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*ReactNode—Child components that consume chess context
fenstring"start"FEN string for initial position
pgnstring—PGN 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
classNamestring—CSS class for the board wrapper
styleCSSProperties—Inline 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) => void—Called when a move is clicked
currentMoveIndexnumber—Index 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
headersPGNHeaders—PGN header metadata (Event, Players, etc.)
widthstring | number—Panel width
classNamestring—CSS class
styleCSSProperties—Inline styles

ComponentNavigation

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

PropTypeDefaultDescription
onFirst() => void—Called when First button clicked (uses context if omitted)
onPrevious() => void—Called when Previous button clicked
onNext() => void—Called when Next button clicked
onLast() => void—Called when Last button clicked
canGoForwardboolean—Enable/disable next and last buttons
canGoBackwardboolean—Enable/disable first and previous buttons
classNamestring—CSS class

ComponentBoardControls

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

PropTypeDefaultDescription
onFlip() => void—Called when flip button clicked (uses context if omitted)
showFlipButtonbooleantrueShow the flip board button
classNamestring—CSS 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) => void—Fires after every legal move. Receives origin/destination squares and the chess.js Move object.
onCheck(color: PieceColor) => void—Fires when a side is placed in check. Receives the color in check.
onGameOver(result: GameOverResult) => void—Fires on checkmate, stalemate, or draw. Result includes winner and reason.
onPromotion(from: Key, to: Key, piece: PromotionPiece) => void—Fires after pawn promotion. Receives the chosen piece type.
onIllegalMove(from: string, to: string) => void—Fires when a player attempts an illegal move.
onFlip(orientation: PieceColor) => void—Fires when the board orientation changes.
onPositionChange(fen: string, moves: Move[]) => void—Fires 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 | null—Raw Chessground API instance for advanced control
gameChess | null—chess.js game instance for direct game state access
flip()() => void—Flip the board orientation
navigateToMove(i)(index: number) => void—Jump to a specific move by index
goFirst()() => void—Navigate to the starting position
goPrevious()() => void—Navigate to the previous move
goNext()() => void—Navigate to the next move
goLast()() => void—Navigate 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*string—CSS color for light squares
darkSquare*string—CSS color for dark squares
selectedSquarestring—Highlight color for the selected piece square
lastMoveHighlightstring—Highlight color for the last move squares
moveDestinationstring—Indicator color for legal move destinations
checkHighlightstring—Highlight 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";