skip to Main Content

I have an array of elements and I want to display them in a div, when the array is big some elements are outside my parent div, I want to detect which ones are outside to make some operations.

this is my example :

export default function App() {
  const data = [
    { id: 1, name: "test1" },
    { id: 2, name: "test2" },
    { id: 3, name: "test3" },
    { id: 4, name: "test4" },
    { id: 5, name: "test5" },
    { id: 6, name: "test6" },
    { id: 7, name: "test7" },
    { id: 8, name: "test8" }
  ];
  return (
    <div
      style={{
        height: "120px",
        background: "red",
        display: "flex",
        flexDirection: "column"
      }}
    >
      {data.map((el) => (
        <div key={el.id}>{el.name}</div>
      ))}
    </div>
  );
}

For the moment I get this :
enter image description here

So, the output should be :

{ id: 7, name: "test7" },
{ id: 8, name: "test8" }

the goal of this is to display in parent ONLY the elements that parent can support to display, forthe others I will display it in other div

2

Answers


  1. To detect which elements are outside the parent div, you can make use of React refs and DOM measurements.

    import React, { useEffect, useRef, useState } from "react";
    
    import VisibleItems from "./VisibleItems";
    
    export default function App() {
      const parentRef = useRef(null);
      const [visibleItems, setVisibleItems] = useState([]);
      const data = Array.from(new Array(10)).map((el, i) => ({
        id: i,
        name: `test ${i}`
      }));
    
      useEffect(() => {
        const handleResize = () => {
          requestAnimationFrame(() => {
            if (parentRef.current) {
              const parentHeight = parentRef.current.clientHeight;
              const children = Array.from(parentRef.current.children);
              let totalHeight = 0;
              let visibleItems = [];
              for (let i = 0; i < children.length; i++) {
                totalHeight += children[i].clientHeight;
                if (totalHeight <= parentHeight) {
                  visibleItems.push(data[i]); // Corrected this line
                } else {
                  break;
                }
              }
              setVisibleItems(visibleItems);
            }
          });
        };
    
        handleResize(); // Initial calculation
        window.addEventListener("resize", handleResize);
    
        return () => {
          window.removeEventListener("resize", handleResize);
        };
      }, [data]);
    
      return (
        <div
          ref={parentRef}
          style={{
            height: "120px",
            background: "red",
            display: "flex",
            flexDirection: "column",
            overflow: "hidden"
          }}
        >
          {visibleItems.map((el) => (
            <VisibleItems key={el.id} visibleItems={visibleItems} />
          ))}
        </div>
      );
    }
    

    and created a new component for VisibleItems

    import React from "react";

    const VisibleItems = ({ visibleItems }) => {
      return (
        <div>
          {visibleItems.map((el) => (
            <div key={el.id}>{el.name}</div>
          ))}
        </div>
      );
    };
    
    export default VisibleItems;
    
    Login or Signup to reply.
  2. Since your parent div is fixed height of 120px, if you give the children fixed height as well then you can easily calculate the children that will contain inside the parent.
    if child height is 30px, then the parent can only contain 120/30= 4 children.

    I don’t think there is any specific way to detect a child overflowing it’s parent.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search