react-chess / chessground

Chessground React Wrapper
https://www.npmjs.com/package/@react-chess/chessground
GNU General Public License v3.0
29 stars 5 forks source link

Expose API via useImperativeHandle. #16

Open isofarro opened 12 months ago

isofarro commented 12 months ago

Following on from the suggestion in #14 , reimplemented my changes using a forwardRef and useImperativeHandle. Returns an instance of the Chessground API for the current board.

Sample code demonstrating it's use (added to the README too):

import { useEffect, useRef } from "react";
import Chessground, { Api, Config, Key } from "@react-chess/chessground";

// these styles must be imported somewhere
import "chessground/assets/chessground.base.css";
import "chessground/assets/chessground.brown.css";
import "chessground/assets/chessground.cburnett.css";

const CONFIG: Config = {
  movable: { free: false },
};

// Demo game moves in long algebraic form
const MOVES = (
  "e2e4 e7e5 g1f3 d7d6 d2d4 c8g4 d4e5 g4f3 d1f3 d6e5 " +
  "f1c4 g8f6 f3b3 d8e7 b1c3 c7c6 c1g5 b7b5 c3b5 c6b5 " +
  "c4b5 b8d7 e1c1 a8d8 d1d7 d8d7 h1d1 e7e6 b5d7 f6d7 " +
  "b3b8 d7b8 d1d8"
).split(" ");

export const DemoGameMoves = () => {
  const apiRef = useRef<Api | undefined>();

  useEffect(() => {
    // Make a move every 2 seconds
    const interval = setInterval(() => {
      const move = MOVES.shift();
      if (move) {
        apiRef.current!.move(move.substring(0,2) as Key, move.substring(2,4) as Key);
      } else {
        clearInterval(interval);
      }
    }, 2000);
    return () => clearInterval(interval);
  });

  return (
    <Chessground
        width={640} height={640}
        config={CONFIG} ref={apiRef}
    />
  );
};
nowszy94 commented 11 months ago

Would be nice to have api usage example in README.md

isofarro commented 11 months ago

Would be nice to have api usage example in README.md

I've added the example demo-game component from this PR description to the README, and added ref to the props documentation.