4.5.0 • Published 2 months ago

react-chessboard v4.5.0

Weekly downloads
4
License
MIT
Repository
github
Last release
2 months ago

react-chessboard

The React Chessboard Library used at ChessOpenings.co.uk

Inspired and adapted from the unmaintained chessboardjsx

Pull Requests Version MIT License

What is react-chessboard?

react-chessboard is a React component that provides chessboard functionality to your application. The Chess game logic that controls the board should be independent to the board, using a library such as Chess.js. An example of these two working together is shown in the example below. For interactive examples visit https://react-chessboard.vercel.app/.

ChessOpenings.co.uk was originally built utilising the chessboardjsx library. With chessboardjsx being unmaintained, it made it difficult to add functionality or optimise performance, so react-chessboard was made.

Installation

npm i react-chessboard

Examples

Storybook

Features

Current

  • Accessible Functions
    • chessboardRef.current.clearPremoves();, takes optional boolean parameter clearLastPieceColour to allow/disallow further premoves of the last moved piece color. Default: true
  • Board Orientation Choice
  • Custom Actions
    • getPositionObject
    • onArrowsChange
    • onDragOverSquare
    • onMouseOutSquare
    • onMouseOverSquare
    • onPieceClick
    • onPieceDragBegin
    • onPieceDragEnd
    • onPieceDrop
    • onPromotionCheck
    • onSquareClick
    • onSquareRightClick
  • Customisable Board Styles
  • Customisable Pieces
  • Customisable Square Styles
  • Customisable Notation Styles
  • Drag and Drop
  • Draw Arrows with Drag or Props
  • Mobile Compatibility
  • Moving Piece Animations
  • Optional Square Coordinates Notation
  • Position Control
  • Premoves
  • Promotion Piece Select
  • Responsive Board Width
  • TypeScript Support

Usage

Bare Minimum

import { Chessboard } from "react-chessboard";

export default function App() {
  return (
    <div>
      <Chessboard id="BasicBoard" />
    </div>
  );
}

Basic Example

IMPORTANT: Examples use the current stable release of chess.js. As of writing this, chess.js v1.0.0 is still in beta. These examples use chess.js ^0.12.0

import { useState } from "react";
import Chess from "chess.js";
import { Chessboard } from "react-chessboard";

export default function PlayRandomMoveEngine() {
  const [game, setGame] = useState(new Chess());

  function makeAMove(move) {
    const gameCopy = { ...game };
    const result = gameCopy.move(move);
    setGame(gameCopy);
    return result; // null if the move was illegal, the move object if the move was legal
  }

  function makeRandomMove() {
    const possibleMoves = game.moves();
    if (game.game_over() || game.in_draw() || possibleMoves.length === 0)
      return; // exit if the game is over
    const randomIndex = Math.floor(Math.random() * possibleMoves.length);
    makeAMove(possibleMoves[randomIndex]);
  }

  function onDrop(sourceSquare, targetSquare) {
    const move = makeAMove({
      from: sourceSquare,
      to: targetSquare,
      promotion: "q", // always promote to a queen for example simplicity
    });

    // illegal move
    if (move === null) return false;
    setTimeout(makeRandomMove, 200);
    return true;
  }

  return <Chessboard position={game.fen()} onPieceDrop={onDrop} />;
}

Advanced Examples

For more advanced code usage examples, please see example boards shown in Storybook.

Props

PropDefault ValueOptionsDescription
allowDragOutsideBoardboolean: falsetrue, falseWhether or not to allow pieces to be dragged outside the board.
animationDurationnumber: 300Time in milliseconds for piece to slide to target square. Only used when the position is programmatically changed. If a new position is set before the animation is complete, the board will cancel the current animation and snap to the new position.
areArrowsAllowedboolean: truetrue, falseWhether or not arrows can be drawn with right click and dragging.
arePiecesDraggableboolean: truetrue, falseWhether or not all pieces are draggable.
arePremovesAllowedboolean: falsetrue, falseWhether or not premoves are allowed.
autoPromoteToQueenboolean: falsetrue, falseWhether or not to automatically promote pawn to queen.
boardOrientationstring: 'white''white', 'black'The orientation of the board, the chosen colour will be at the bottom of the board.
boardWidthnumber: 560The width of the board in pixels.
clearPremovesOnRightClickboolean: truetrue, falseIf premoves are allowed, whether or not to clear the premove queue on right click.
customArrowColorstring: 'rgb(255,170,0)'rgb or hex stringString with rgb or hex value to colour drawn arrows.
customArrowsSquare, Square, string?[]array of string arraysArray where each element is a tuple containing two Square values (representing the 'from' and 'to' squares) and an optional third string element for the arrow color e.g. [ 'a3', 'a5', 'red', 'g1', 'f3' ].
customBoardStyleobject: {}inline CSS stylingCustom board style object e.g. { borderRadius: '5px', boxShadow: '0 5px 15px rgba(0, 0, 0, 0.5 '}.
customNotationStyleobject: {}inline CSS stylingCustom notation style object e.g. { fontSize: '12px' }.
customDarkSquareStyleobject: { backgroundColor: '#B58863' }inline CSS stylingCustom dark square style object.
customDndBackendBackendFactory: undefinedCustom react-dnd backend to use instead of the one provided by react-chessboard.
customDndBackendOptionsany: undefinedOptions to use for the given custom react-dnd backend. See customDndBackend.
customDropSquareStyleobject: { boxShadow: 'inset 0 0 1px 6px rgba(255,255,255,0.75)' }inline CSS stylingCustom drop square style object (Square being hovered over with dragged piece).
customLightSquareStyleobject: { backgroundColor: '#F0D9B5' }inline CSS stylingCustom light square style object.
customPiecesobject: {}Custom pieces object where each key must match a corresponding chess piece (wP, wB, wN, wR, wQ, wK, bP, bB, bN, bR, bQ, bK). The value of each piece is a function that takes in some optional arguments to use and must return JSX to render. e.g. { wK: ({ isDragging: boolean, squareWidth: number, droppedPiece: string, targetSquare: string, sourceSquare: string }) => jsx }.
customPremoveDarkSquareStyleobject: { backgroundColor: '#A42323' }inline CSS stylingCustom premove dark square style object.
customPremoveLightSquareStyleobject: { backgroundColor: '#BD2828' }inline CSS stylingCustom premove light square style object.
customSquareElementType: "div"Custom renderer for squares. Can also use an html element.
customSquareStylesobject: {}inline CSS stylingCustom styles for all squares.
idnumber: 0string, numberBoard identifier, necessary if more than one board is mounted for drag and drop.
isDraggablePiecefunction: ({ piece, sourceSquare }) => truereturns true, falseFunction called when a piece drag is attempted. Returns if piece is draggable.
getPositionObjectfunction: (currentPosition) => {}User function that receives current position object when position changes.
onArrowsChangefunction: (squares) => {}User function is run when arrows are set on the board.
onDragOverSquarefunction: (square) => {}User function that is run when piece is dragged over a square.
onMouseOutSquarefunction: (square) => {}User function that is run when mouse leaves a square.
onMouseOverSquarefunction: (square) => {}User function that is run when mouse is over a square.
onPieceClickfunction: (piece, square) => {}User function that is run when piece is clicked.
onPieceDragBeginfunction: (piece, sourceSquare) => {}User function that is run when piece is grabbed to start dragging.
onPieceDragEndfunction: (piece, sourceSquare) => {}User function that is run when piece is let go after dragging.
onPieceDropfunction: (sourceSquare, targetSquare, piece) => truereturns true, falseUser function that is run when piece is dropped on a square. Must return whether the move was successful or not. This return value does not control whether or not the piece was placed (as that is controlled by the position prop) but instead controls premove logic.
onPromotionCheckfunction: (sourceSquare, targetSquare, piece) => (((piece === "wP" && sourceSquare1 === "7" && targetSquare1 === "8") || (piece === "bP" && sourceSquare1 === "2" && targetSquare1 === "1")) && Math.abs(sourceSquare.charCodeAt(0) - targetSquare.charCodeAt(0)) <= 1)returns true, falseUser function that is run when piece is dropped. Must return whether the move results in a promotion or not.
onSquareClickfunction: (square, piece) => {}User function that is run when a square is clicked.
onSquareRightClickfunction: (square) => {}User function that is run when a square is right clicked.
positionstring: 'start''start', FEN string, { e5: 'wK', e4: 'wP', ... }FEN string or position object notating where the chess pieces are on the board. Start position can also be notated with the string: 'start'.
promotionDialogVariantstring: 'default':'default', 'vertical', 'modal'Style of promotion dialog.
promotionToSquarestring or null'a1', 'a2', ..., 'h8', nullThe square to promote a piece to. Must be passed when promotion dialog is manually shown.
showBoardNotationboolean: truetrue, falseWhether or not to show the file and rank co-ordinates (a..h, 1..8).
showPromotionDialogboolean: falsetrue, falseWhether or not to manually show the promotion dialog.
snapToCursorboolean: truetrue, falseWhether or not to center dragged pieces on the mouse cursor.

Contributing

  1. Fork this repository
  2. Clone your forked repository onto your development machine
    git clone https://github.com/yourUsernameHere/react-chessboard.git
    cd react-chessboard
  3. Create a branch for your PR
    git checkout -b your-branch-name
  4. Set upstream remote
    git remote add upstream https://github.com/Clariity/react-chessboard.git
  5. Make your changes
  6. Test your changes by running storybook
    npm run storybook
  7. Push your changes
    git add .
    git commit -m "feature/cool-new-feature"
    git push --set-upstream origin your-branch-name
  8. Create pull request on GitHub
  9. Contribute again
    git checkout main
    git pull upstream main
    git checkout -b your-new-branch-name

LICENSE

MIT

4.5.0

2 months ago

4.4.0

3 months ago

4.3.4

4 months ago

4.3.3

4 months ago

4.2.3

7 months ago

4.2.2

7 months ago

4.3.2

6 months ago

4.3.1

6 months ago

4.3.0

6 months ago

4.2.1

7 months ago

4.2.0

8 months ago

3.2.0

10 months ago

3.0.1

11 months ago

3.0.0

11 months ago

4.0.1

10 months ago

4.0.0

10 months ago

3.1.1

10 months ago

3.1.0

11 months ago

4.1.0

8 months ago

2.0.8

1 year ago

2.1.2

1 year ago

2.1.1

1 year ago

2.1.3

1 year ago

2.1.0

1 year ago

1.3.1

1 year ago

2.0.3

1 year ago

2.0.2

1 year ago

2.0.5

1 year ago

2.0.4

1 year ago

2.0.7

1 year ago

2.0.6

1 year ago

2.0.1

1 year ago

2.0.0

1 year ago

1.2.8

2 years ago

1.2.7

2 years ago

1.2.6

2 years ago

1.2.5

2 years ago

1.2.4

2 years ago

1.3.0

2 years ago

1.2.3

2 years ago

1.2.2

2 years ago

1.2.0

2 years ago

1.0.2

2 years ago

1.1.0

2 years ago

1.0.1

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.2.1

2 years ago

1.0.3

2 years ago

1.0.0

2 years ago

0.0.17

2 years ago

0.0.18

2 years ago

0.0.16

3 years ago

0.0.11

3 years ago

0.0.12

3 years ago

0.0.13

3 years ago

0.0.14

3 years ago

0.0.15

3 years ago

0.0.10

3 years ago

0.0.9

3 years ago

0.0.8

3 years ago

0.0.7

3 years ago

0.0.6

3 years ago

0.0.5

3 years ago

0.0.4

3 years ago

0.0.3

3 years ago

0.0.2

3 years ago

0.0.1

9 years ago