Skip to content

Instantly share code, notes, and snippets.

@ruvasik
Created December 13, 2023 11:59
Show Gist options
  • Save ruvasik/9b9ba7278254e7de67c11bcf6ca98fa6 to your computer and use it in GitHub Desktop.
Save ruvasik/9b9ba7278254e7de67c11bcf6ca98fa6 to your computer and use it in GitHub Desktop.
Dynamic ViewPort variable in css/sc
import React, {
RefObject,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { Portal } from "@mui/base";
import { Box } from "@mui/material";
import log from "@utils/log";
const wv = (v: number) => `calc(var(--wv) * ${v})`;
let ref: RefObject<HTMLElement>;
const getW = (ref: RefObject<HTMLElement>) =>
ref.current?.getBoundingClientRect()?.width || undefined;
export const useDynamicWv = (
gRef?: RefObject<HTMLElement>
): number | undefined => {
const [value, setValue] = useState<number | undefined>(undefined);
if (gRef) ref = gRef;
if (!ref) throw Error("Not correct called useDynamicWv");
const onResize = useCallback(() => {
setValue(getW(ref));
}, []);
useEffect(() => {
setValue(getW(ref));
window.addEventListener("resize", onResize);
return () => {
window.removeEventListener("resize", onResize);
};
}, []);
return value;
};
export const WV = React.memo(() => {
const ref = useRef(null);
useDynamicWv(ref);
return (
<>
<Box
id="wvportal"
ref={ref}
sx={{ position: "absolute", height: 1, width: wv(1) }}
/>
<Portal container={ref.current}></Portal>
</>
);
});
WV.displayName = "BrowserWV";
export default wv;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment