Skip to content

Instantly share code, notes, and snippets.

@Stanley-Yao
Last active August 15, 2021 03:56
Show Gist options
  • Save Stanley-Yao/6735f6691b60148d1cc39d8a0c03d4ff to your computer and use it in GitHub Desktop.
Save Stanley-Yao/6735f6691b60148d1cc39d8a0c03d4ff to your computer and use it in GitHub Desktop.
get-ref-width
import React, { useEffect, useRef, useState } from "react";
const AppBeta = () => {
const [width, setWidth] = useState<number>(window.innerWidth);
const [widgetBWidth, setWidgetBWidth] = useState<number | undefined>();
const widgetBContainer = useRef<HTMLDivElement>(null);
const updateWidth = () => {
setWidth(window.innerWidth);
};
useEffect(() => {
window.addEventListener("resize", updateWidth);
}, []);
useEffect(() => {
setWidgetBWidth(widgetBContainer?.current?.offsetWidth);
}, [widgetBContainer?.current?.offsetWidth]);
return (
<>
<h3> App Beta </h3>
<h3> App Width: {width} px </h3>
<div className="container-beta">
<div className="child-app-C">Widget C</div>
<div className="child-app-B" ref={widgetBContainer}>
Widget B width: <div>{widgetBWidth} px</div>
</div>
</div>
</>
);
};
export default AppBeta;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment