Skip to content

Instantly share code, notes, and snippets.

@gabrielmlinassi
Created September 9, 2021 04:07
Show Gist options
  • Save gabrielmlinassi/29bd3fc17b5b0017bbcd9d5bc24d9324 to your computer and use it in GitHub Desktop.
Save gabrielmlinassi/29bd3fc17b5b0017bbcd9d5bc24d9324 to your computer and use it in GitHub Desktop.
workaround aspect-ratio safari
import { useRef, useEffect, useState } from "react";
export default function Test() {
const [height, setHeight] = useState(0);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (ref.current) {
setHeight((ref.current.clientWidth * 16) / 9);
}
}, [ref]);
return (
<div className="flex items-center justify-center w-screen h-screen bg-green-400">
<div
style={{ height: `${height}px` }}
ref={ref}
className="w-96 rounded-md shadow-md bg-green-700"
/>
</div>
);
return (
<div className="flex items-center justify-center w-screen h-screen bg-green-400">
<div
style={{ aspectRatio: "9/16" }}
className="w-96 rounded-md shadow-md bg-green-700"
/>
</div>
);
}
@mesterum
Copy link

mesterum commented Feb 6, 2022

const _targetsParam=new Map()
const _resizeObserver = new ResizeObserver(entries => {
  for (let entry of entries) {
    const width =
      (entry.contentBoxSize
        ?(entry.contentBoxSize[0]
            ?entry.contentBoxSize[0]
            :entry.contentBoxSize
        ).inlineSize
        :entry.contentRect.width
      )
    const {setHeight, WHratio} = _targetsParam.get(entry.target)
    setHeight(width / WHratio)
  }
  console.log('Size changed');
});
const useHeightOnAspectRatio = (WHratio) => {
  const [height, setHeight] = useState(0);
  const oldRef=useRef(null)
  const ref = useCallback(node => {
    if (oldRef.current != null){
      const node=oldRef.current
      _resizeObserver.unobserve(node);
      _targetsParam.delete(node)
    }
    if (node != null) {
      _targetsParam.set(node, {setHeight, WHratio})
      _resizeObserver.observe(node);
      oldRef.current=node
    }
  }, []);
  return [height, ref]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment