Skip to content

Instantly share code, notes, and snippets.

@programarivm
Created May 1, 2023 22:19
Show Gist options
  • Save programarivm/89260aa40def3255802b203efb3f1565 to your computer and use it in GitHub Desktop.
Save programarivm/89260aa40def3255802b203efb3f1565 to your computer and use it in GitHub Desktop.
Selecting multiple elements
import React, { useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import Ascii from '../common/Ascii';
import Pgn from '../common/Pgn';
import Piece from '../common/Piece';
// ...
const Board = ({props}) => {
const state = useSelector(state => state);
const dispatch = useDispatch();
// ...
const sqsRef = useRef([]);
const imgsRef = useRef([]);
// ...
const handleMove = (payload) => {
// ...
};
const board = () => {
return Ascii.flip(
state.board.flip,
state.board.history[state.board.history.length - 1 + state.history.back]
).map((rank, i) => {
return rank.map((piece, j) => {
let payload = { piece: piece };
let color = (i + j) % 2 !== 0
? Pgn.symbol.BLACK
: Pgn.symbol.WHITE;
state.board.flip === Pgn.symbol.WHITE
? payload = {
...payload,
i: i,
j: j,
sq: Ascii.fromIndexToAlgebraic(i, j)
}
: payload = {
...payload,
i: 7 - i,
j: 7 - j,
sq: Ascii.fromIndexToAlgebraic(7 - i, 7 - j)
};
// ...
return <div
key={payload.sq}
ref={el => sqsRef.current[payload.sq] = el}
onClick={() => {
handleMove(payload);
}}
onDrop={(ev) => {
ev.preventDefault();
handleMove(payload);
}}
onDragOver={(ev) => {
ev.preventDefault();
}}>
{
Piece.unicode[piece].char
? <img
ref={el => imgsRef.current[payload.sq] = el}
src={Piece.unicode[piece].char}
draggable={Piece.color(piece) === state.board.turn ? true : false}
onDragStart={() => handleMove(payload)}
/>
: null
}
</div>
});
});
}
return (
<div>
{board()}
</div>
);
}
export default Board;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment