Skip to content
This repository has been archived by the owner on Feb 19, 2022. It is now read-only.

Commit

Permalink
use aspect-ratio
Browse files Browse the repository at this point in the history
  • Loading branch information
sapphi-red committed Dec 31, 2021
1 parent d3e7eca commit 2cd670a
Showing 1 changed file with 2 additions and 22 deletions.
24 changes: 2 additions & 22 deletions client/src/components/foundation/AspectRatioBox/AspectRatioBox.jsx
Expand Up @@ -12,29 +12,9 @@ import React from 'react';
* @type {React.VFC<Props>}
*/
const AspectRatioBox = ({ aspectHeight, aspectWidth, children }) => {
/** @type {React.RefObject<HTMLDivElement>} */
const ref = React.useRef(null);
const [clientHeight, setClientHeight] = React.useState(0);

React.useEffect(() => {
// clientWidth とアスペクト比から clientHeight を計算する
function calcStyle() {
const clientWidth = ref.current.clientWidth;
setClientHeight((clientWidth / aspectWidth) * aspectHeight);
}
setTimeout(() => calcStyle(), 500);

// ウィンドウサイズが変わるたびに計算する
window.addEventListener('resize', calcStyle, { passive: true });
return () => {
window.removeEventListener('resize', calcStyle);
};
}, [aspectHeight, aspectWidth]);

return (
<div ref={ref} className="relative w-full h-1" style={{ height: clientHeight }}>
{/* 高さが計算できるまで render しない */}
{clientHeight !== 0 ? <div className="absolute inset-0">{children}</div> : null}
<div className="relative w-full" style={{ aspectRatio: `${aspectWidth} / ${aspectHeight}` }}>
{children}
</div>
);
};
Expand Down

0 comments on commit 2cd670a

Please sign in to comment.