MaterialUI: How to limit the height of a grid item to the height of other grid item at maximum?

Viewed 14

I'm trying to make a grid with 4 items. The fourth item is taller than the rest of the items, and is thus dictating the overall grid height. Is there a way to limit heigh of the fourth item (h4) to the height of the first item (h1) so that h4 = Grid height = h1?

<Grid container xs={12} spacing={4}>
    <Grid xs={3}>
        {*/ short item /*}
    </Grid>
    <Grid xs={3}>
        {*/ short item /*}
    </Grid>
    <Grid xs={3}>
        {*/ short item /*}
    </Grid>
    <Grid xs={3}>
        {*/ long item /*}
    </Grid>
</Grid>

Here's a sandbox

picture

1 Answers

Definitely not sure if it's the cleanest solution, but I used a custom hook (I didn't develop it) to get the clientRect of the first item, and set the max-height to that on the clientRect

/**
 * Generate a ref and BoundingClientRect that will be updated when the ref is updated
 * on resize or scroll
 * https://gist.github.com/morajabi/523d7a642d8c0a2f71fcfa0d8b3d2846?permalink_comment_id=3925412#gistcomment-3925412
 * @returns [rect, ref]
 */
export const useRect = <T extends Element>(): [
  DOMRect | undefined,
  MutableRefObject<T | null>
] => {
  const ref = useRef<T>(null);
  const [rect, setRect] = useState<DOMRect>();

  const set = () => setRect(ref.current?.getBoundingClientRect());

  const useEffectInEvent = (
    event: "resize" | "scroll",
    useCapture?: boolean
  ) => {
    useEffect(() => {
      set();
      window.addEventListener(event, set, useCapture);
      return () => window.removeEventListener(event, set, useCapture);
    }, []);
  };

  useEffectInEvent("resize");
  useEffectInEvent("scroll", true);

  return [rect, ref];
};

important lines: setting ref:

<Grid xs={3}>
  <Box ref={ref}>
    {*/ short item content/*}
  </Box>
</Grid>

setting height (on fourth item):

<Grid xs={3}>
  <Box
    sx={{  maxHeight: rect.height, overflowY: "scroll" }}
  >
    {/* long item content */}
  </Box>
</Grid>

heres the complete sandbox

Related