Resizing a component relative to it’s parent (position: fixed)

In the previous post I mentioned how we can fix a footer to the bottom of the viewport, but we have an issue where the width extends outside the width of the parent.

NOTE: This post discusses a partial solution to this issue. In that, if the browser window size changes this works, but if your viewport size changes, it doesn’t. So for example if you have a flyout Drawer component or the likes which takes up space on the page, then no window resize takes place, only a layout change takes place. If I resolve this I’ll update this post.

To solve this we’re going to create a ref on our parent div and monitor it’s size changes and then apply them to our footer.

So assuming we’re using material-ui’s createStyle, with the following CSS (or use plain CSS or your preferred CSS library)

footer: {
  position: "fixed",
  bottom: 0,
  marginBottom: "10px",
  textAlign: "left",
},

Here’s an abridged version of my code (using a React functional component)

const targetRef: any = useRef(null);
const [relativeWidth, setRelativeWidth] = useState(0);

useLayoutEffect(() => {
  function updateWidth() {
    if (targetRef != null && targetRef.current != null) {
      setRelativeWidth(targetRef.current.offsetWidth);
    }
  }

  window.addEventListener("resize", updateWidth);
  updateSize();
  return () => window.removeEventListener("resize", updateWidth);
}, []);

return (
  <div ref={targetRef}>
    {/* our other elements */}
    <div className={classes.footer}
      style={{ width: relativeWidth }}>
      {/* our footer elements */}
    </div>
  </div>
);

So what we’re doing is getting a ref to the parent div and storing the relativeWidth in the component’s state using useState (which we set up at the start of the function). Using useEffect, we create a listener to the window’s resize events and then update our state. Finally in the footer style we set the width explicitly using then relativeWidth that we stored.

Not only will this now display correctly relative to the parent div, but also resize relative to it as well.

These are early days for this code, but so far this looks to work a treat.