Currently, I am in the process of developing a chess application and encountered a scenario where I needed the board size to dynamically adjust to the window size while maintaining a square aspect ratio (width equals height). To address this, I created my own custom hook which functions effectively. Nevertheless, I am curious to explore other potential solutions for this particular challenge. Below is the custom hook I devised:
import { useEffect, useState } from "react";
const getDimensions = () => {
return document.documentElement.clientWidth > document.documentElement.clientHeight
? { boardSize: "100vh", pieceSize: "10vh"}
: { boardSize: "100vw", pieceSize: "10vw"};
};
function useDimensions() {
let [dimensions, setDimensions] = useState(getDimensions());
useEffect(() => {
const handleResize = () => {
setDimensions(getDimensions());
};
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
}, []);
return dimensions;
}
export default useDimensions;
Within my board component, I easily utilize
let boardSize = useDimensions().boardSize;
and then incorporate boardSize in the JSX styling.