Reputation: 1242
I'm making a simple chess app and wanted the board size to responsively fill the window while remaining square (width = height). I ended up making my first custom hook, and it works well, but I wanted to know if there are better solutions to this problem. My hook:
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;
In my board component I simply let boardSize = useDimensions().boardSize;
and then reference boardSize in the jsx style.
Upvotes: 0
Views: 30
Reputation: 196027
You could use { boardSize: "100vmin", pieceSize: "10vmin"}
and be done without any js.
vmin
Equal to the smaller ofvw
andvh
.
See https://developer.mozilla.org/en-US/docs/Web/CSS/length#vmin
Upvotes: 1