Search code examples
reactjsreact-dnd

React dnd - chessboard tutorial example issue


I want to make the knight could move to any square (NOT follow the game rule). So I change the function: canMoveKnight in file Game.js like this:

canMoveKnight(toX, toY) {
    return true;  
}

The result is: the knight CANNOT move at all.

But if I change the function to:

canMoveKnight(toX, toY) {
    const [x, y] = this.knightPosition
    return (x !== toX || y !== toY)
}

basically, just exclude the knight position. Still return TRUE in other squares. It works.

Anyone could help to explain why return TRUE for all squares NOT working?

You can play with the source code here: https://codesandbox.io/s/github/react-dnd/react-dnd/tree/gh-pages/examples_hooks_js/00-chessboard?from-embed

Fortunately, I think someone answer the question before it closed.

I tried the answer. by adding the zIndex to Knight, it does work.

Without the zIndex, the BoardSquare catch the mouse event, and BoardSquare is NOT draggable.


Solution

  • This is kind of a weird issue you ran into! I would love to hear anyone else's answer on this as well, as I am still very curious about the cause of the issue. I did find a solution for you though!

    It seems like the knight piece is somehow blocked from being clicked on if it is on a tile that is also a valid move. (If anyone can figure out why please share)

    To fix the problem you can add position: absolute to the knight as well as z-index: <value>. This makes the knight div appear above everything else so it is still draggable.

    Specifically, you can change your knightStyle in Knight.jsx to this:

    const knightStyle = {
        fontSize: 40,
        fontWeight: 'bold',
        cursor: 'move',
        position: 'absolute',
        zIndex: 50,
    };